Angular2或TypeScript左用零填充字符串 [英] Angular2 or TypeScript Left padding a String with Zeros

查看:134
本文介绍了Angular2或TypeScript左用零填充字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数字,可以说9.但是我需要它作为字符串"09".

I have a number let say 9. But I need it as String "09".

我知道我可以写自己的逻辑.但是我正在寻找一个可以填充它的隐式util函数.

I know i can write my own logic. But I am looking for a implicit util function which can pad it.

我将angular2与TypeScript一起使用.寻找类似的内容.

I am using angular2 with TypeScript. Looking for something like this.

就像Java一样

String.format("%010d", Integer.parseInt(mystring));

推荐答案

您可以为此创建自己的函数.要格式化数字,您必须先将其转换为字符串.

You can create your own function for this. To format the number you will have to convert it to a string first.

function pad(num, size) {
    let s = num+"";
    while (s.length < size) s = "0" + s;
    return s;
}

TypeScript

TypeScript

pad(num:number, size:number): string {
    let s = num+"";
    while (s.length < size) s = "0" + s;
    return s;
}

编辑:有两种更好,更高效的方法来执行此操作. 请参阅此答案中的讨论: https://stackoverflow.com/a/9744576/1734678 (我建议阅读大多数如果有时间,提交的答案)

There are a couple of better and more performant ways to do this. See the discussion in this Answer: https://stackoverflow.com/a/9744576/1734678 (I recommend reading most of the submitted answers if you got time)

更新:ECMAScript 2017现在支持字符串填充

Update: ECMAScript 2017 now has support for string padding

str.padStart(targetLength [, padString])
str.padEnd(targetLength [, padString])

检查 https://developer.mozilla .org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/padStart

这篇关于Angular2或TypeScript左用零填充字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆