如何用前导零填充值? [英] How can I pad a value with leading zeros?
问题描述
在JavaScript中对值进行zerofill的推荐方法是什么?我想我可以构建一个自定义函数来将零填充到一个类型化的值,但我想知道是否有更直接的方法来做到这一点?
What is the recommended way to zerofill a value in JavaScript? I imagine I could build a custom function to pad zeros on to a typecasted value, but I'm wondering if there is a more direct way to do this?
注意:通过zerofilled我的意思是它在数据库意义上的单词(其中数字5的6位零填充表示将是000005)。
Note: By "zerofilled" I mean it in the database sense of the word (where a 6-digit zerofilled representation of the number 5 would be "000005").
推荐答案
读者注意!
Note to readers!
正如评论者指出的那样,这个解决方案是聪明的,并且由于b $ b聪明的解决方案经常是,它的内存密集且相对
慢。如果您担心性能问题,请不要使用此解决方案!
As commenters have pointed out, this solution is "clever", and as clever solutions often are, it's memory intensive and relatively slow. If performance is a concern for you, don't use this solution!
可能已过时 :ECMAScript 2017包括 String.prototype.padStart 和<一个href =https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString =noreferrer> Number.prototype.toLocaleString ECMAScript 3.1。示例:
Potentially outdated: ECMAScript 2017 includes String.prototype.padStart and Number.prototype.toLocaleString is there since ECMAScript 3.1. Example:
var n=-0.1;
n.toLocaleString('en', {minimumIntegerDigits:4,minimumFractionDigits:2,useGrouping:false})
...将输出-0000.10。
...will output "-0000.10".
// or
const padded = (.1+"").padStart(6,"0");
`-${padded}`
...将输出-0000.1。
...will output "-0000.1".
您只需要一个简单的功能
A simple function is all you need
function zeroFill( number, width )
{
width -= number.toString().length;
if ( width > 0 )
{
return new Array( width + (/\./.test( number ) ? 2 : 1) ).join( '0' ) + number;
}
return number + ""; // always return a string
}
如果你想要你可以将它烘焙到一个库中保存命名空间或其他什么。与 jQuery扩展一样。
you could bake this into a library if you want to conserve namespace or whatever. Like with jQuery's extend.
这篇关于如何用前导零填充值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!