Javascript 数字为一位数时保留前导0
我正在使用JavaScript中的parseInt()函数,需要应用逻辑,就像给定的数字小于10一样,然后在数字之前添加0 所以,如果给定的数字是9,则将其打印为09。我申请的是:Javascript 数字为一位数时保留前导0,javascript,function,Javascript,Function,我正在使用JavaScript中的parseInt()函数,需要应用逻辑,就像给定的数字小于10一样,然后在数字之前添加0 所以,如果给定的数字是9,则将其打印为09。我申请的是: if (no < 10) { no = "0" + no; } if(否
if (no < 10) {
no = "0" + no;
}
if(否<10){
否=“0”+否;
}
并在其上应用parseInt()方法,但每次前导零都会闪烁 您必须将其转换为字符串,因为数字对前导零没有意义 因此,您必须将数字打印为:
if (no < 10) {
console.log("0" + no);
}
if(否<10){
控制台日志(“0”+否);
}
如果no=8
,则结果是javascript中的“08”
,则不能有前导零。如果需要前导零,则应将其表示为字符串
parseInt('01', 10); // 1
parseFloat('01'); // 1
parseInt(01, 10); // 1
一个有用的函数,用于向转换为字符串的数字添加填充。请随意将其放入您自己的UTIL或其他帮助工具带中。快乐
/**
* Add padding (leading zero's) to integer, based on minimum length
* @param {Number} integer
* @param {Number} minimal length of returned string
* @return {String} padded string
*/
function addPadding(integer, length){
var integerString = integer + '';
while (integerString.length < length) {
integerString = '0' + integerString;
}
return integerString;
}
// Output examples
addPadding(15, 3); // 015
addPadding(4, 2); // 04
addPadding(123, 2); // 123
addPadding(123, 5); // 00123
/**
*根据最小长度将填充(前导零)添加到整数
*@param{Number}整数
*@param{Number}返回字符串的最小长度
*@return{String}填充字符串
*/
函数addPadding(整数,长度){
var integerString=integer+'';
while(integerString.length
首先,始终使用10的基数和parseInt()
其次,使用console.log()
查看您得到了什么:
no = parseInt(user_input, 10); // base 10
console.log(typeof no);
if (no < 10) {
no = "0" + no;
}
console.log(typeof no);
输入中的前导0
可能会造成阻碍,因为它是八进制表示,并且8
或9
不是有效的数字。输出不能将前导的0
作为数字
,因此必须作为字符串
保存
如果正确地将代码中的实际数字与数字分开,则最后一点不是问题:
no_to_compute = 8; // is a number type
no_to_display = "0" + no; // ia a string type:
// representation of the number (numeral)
如果它已经是一个数字,那么为什么还需要包含parseInt()
?这就是parse int的作用。为什么在为值添加前缀后还需要pars int?分配字符串时,no会转换为字符串。也许这会有帮助:)您必须执行相反的操作,parseInt(),然后进行填充。您应该始终使用带有parseInt
的基数。是的,我知道……快速而肮脏的回答。现在添加了参数:)
no_to_compute = 8; // is a number type
no_to_display = "0" + no; // ia a string type:
// representation of the number (numeral)