在字符串前添加零 [英] adding zeros in front of a string

查看:58
本文介绍了在字符串前添加零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要你的帮助.

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

I'd like to create a function that would add some zeros in front of a number. The maximum numbers of digits that the total string should have is 6. Here are examples:

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

推荐答案

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

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

A simple one line solution without any loops

Works with IE5-11, Firefox, Chrome, etc. Assumes integer input.

 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>

这篇关于在字符串前添加零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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