我想把一个数格式化为两位数。这个问题是在传递0-9时引起的,所以我需要将它格式化为00-09。
JavaScript中有数字格式化器吗?
我想把一个数格式化为两位数。这个问题是在传递0-9时引起的,所以我需要将它格式化为00-09。
JavaScript中有数字格式化器吗?
当前回答
如果您的项目中没有lodash,那么仅仅为了使用一个函数而添加整个库将是一种过度。这是我见过的最复杂的解决你问题的方法。
_.padStart(num, 2, '0')
其他回答
这是我的版本。可以很容易地适应其他场景。
function setNumericFormat(value) {
var length = value.toString().length;
if (length < 4) {
var prefix = "";
for (var i = 1; i <= 4 - length; i++) {
prefix += "0";
}
return prefix + value.toString();
}
return value.toString();
}
如果数字大于9,则将数字转换为字符串(一致性)。否则,加一个零。
function n(n){
return n > 9 ? "" + n: "0" + n;
}
n( 9); //Returns "09"
n(10); //Returns "10"
n(999);//Returns "999"
似乎你得到的是一个字符串,而不是一个数字。用这个:
var num = document.getElementById('input').value,
replacement = num.replace(/^(\d)$/, '0$1');
document.getElementById('input').value = replacement;
这里有一个例子:http://jsfiddle.net/xtgFp/
之前答案的改进版本
函数atLeast2Digit (n) { n = parseInt(n);/ /交货。如果已经经过'05',它将被转换为数字5 Var ret = n > 9 ?" + n: "0" + n; 返回受潮湿腐烂; } alert (atLeast2Digit (5));
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#test').keypress(allowOnlyTwoPositiveDigts);
});
function allowOnlyTwoPositiveDigts(e){
var test = /^[\-]?[0-9]{1,2}?$/
return test.test(this.value+String.fromCharCode(e.which))
}
</script>
</head>
<body>
<input id="test" type="text" />
</body>
</html>