我正在尝试使用以下格式转换数字
0 -> 0.00
1 -> 1.00
1.1 -> 1.10
4.0 -> 4.00
但问题是它只返回字符串
value = 0;
var s = Math.floor(value / 60) + "." + (value % 60 ? value % 60 : '00');
console.log(s+s); //just checking if its number
但它以字符串形式返回,我尝试了parseInt,但它只返回0。我试过ParseFloat and fixedTo(2
),它只返回字符串。
答案 0 :(得分:5)
正如评论中所见,JavaScript中没有办法实现。格式化数字始终返回Srting。为此你有一些可能性,但
Number(1).toFixed(2) // "1.00" - setting the number of digits after the decimal point
Number(1).toPrecision(2) // "1.0" - setting the number of digits
这些用于打印出来,通常情况下,无论是字符串还是数字都无关紧要。
然后,如果您想将其用作数字,只需按照@Max的建议并使用函数Number(str)
或速记+str
进行转换。