我想把一个数格式化为两位数。这个问题是在传递0-9时引起的,所以我需要将它格式化为00-09。
JavaScript中有数字格式化器吗?
我想把一个数格式化为两位数。这个问题是在传递0-9时引起的,所以我需要将它格式化为00-09。
JavaScript中有数字格式化器吗?
当前回答
<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>
其他回答
@Lifehack的回答对我很有用;我想我们可以用一行来表示正数
String(input).padStart(2, '0');
似乎你得到的是一个字符串,而不是一个数字。用这个:
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>
如果数字大于9,则将数字转换为字符串(一致性)。否则,加一个零。
function n(n){
return n > 9 ? "" + n: "0" + n;
}
n( 9); //Returns "09"
n(10); //Returns "10"
n(999);//Returns "999"