我正在尝试将数字转换为以下格式
0 -> 0.00
1 -> 1.00
1.1 -> 1.10
4.0 -> 4.00
Run Code Online (Sandbox Code Playgroud)
但是问题是它仅以字符串形式返回
value = 0;
var s = Math.floor(value / 60) + "." + (value % 60 ? value % 60 : '00');
console.log(s+s); //just checking if its number
Run Code Online (Sandbox Code Playgroud)
但是它以字符串形式返回,我尝试了parseInt,但是它只返回0。我试过ParseFloat and fixedTo(2),它仅以字符串形式返回。
从评论中可以看出,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
Run Code Online (Sandbox Code Playgroud)
这些是用于打印出来的,因此通常情况下,它是字符串还是数字都没有关系。
然后,如果您要将其用作数字,则只需遵循@Max的建议并使用函数Number(str)或速记对其进行转换+str。