gpt4 book ai didi

javascript - 在字符串前加零

转载 作者:数据小太阳 更新时间:2023-10-29 05:42:41 25 4
gpt4 key购买 nike

我需要你的帮助。

我想创建一个函数,在数字前面添加一些零。整个字符串的最大位数应为 6。示例如下:

     9 -> 000009
14 -> 000014
230 -> 000230
1459 -> 001459
21055 -> 021055
987632 -> 987632 (Do nothing, there's already 6 digits)

最佳答案

没有任何循环的简单单行解决方案

适用于 IE5-11、Firefox、Chrome 等。假设为整数输入。

 function pad(n) { return ("000000" + n).slice(-6); }

运行片段进行测试:

<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>

关于javascript - 在字符串前加零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30490968/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com