Bob*_*nes 5 javascript string numbers
我需要你的帮助.
我想创建一个在数字前添加一些零的函数.总字符串应具有的最大位数为6.以下是示例:
9 -> 000009
14 -> 000014
230 -> 000230
1459 -> 001459
21055 -> 021055
987632 -> 987632 (Do nothing, there's already 6 digits)
Run Code Online (Sandbox Code Playgroud)
Rob*_*rto 12
适用于IE5-11,Firefox,Chrome等.假设整数输入.
function pad(n) { return ("000000" + n).slice(-6); }
Run Code Online (Sandbox Code Playgroud)
运行代码段进行测试:
<html>
<body>
<input id="stdin" placeholder="enter a number" maxlength="6"><button onclick="test()">Test</button>
<textarea id="stdout" style="width:100%;height:20em;padding:1em;"></textarea>
<script type="text/javascript">
function pad(n) { return ("000000" + n).slice(-6); }
function test() {
var n = parseInt( document.getElementById('stdin').value);
var e = document.getElementById('stdout').innerHTML += n + ' = ' + pad(n) + '\n';
}
</script>
</body>
</html>Run Code Online (Sandbox Code Playgroud)
以下内容将为数字字符串添加零,直到长度等于6.
var s = '9876'
while(s.length < 6){
s = '0' + s
}
alert(s)
Run Code Online (Sandbox Code Playgroud)
bea*_*mes -2
我已经使用 SugarJs API 很长时间了,它们的填充功能效果很好。
http://sugarjs.com/api/Number/pad
(9).pad(6, true) --> 000009
(14).pad(6, true) --> 000014
Run Code Online (Sandbox Code Playgroud)
ETC...