给我一个本机(请不要使用jQuery,Prototype等。)JavaScript函数,该函数将数字转换如下:
input: 0.39, 2.5, 4.25, 5.5, 6.75, 7.75, 8.5
output: 0.39, 2.50, 4.25, 5.50, 6.75, 7.75, 8.50
例如,在Ruby中,我会做这样的事情:
>> sprintf("%.2f", 2.5)
=> "2.50"
输出可以是数字或字符串。我不在乎,因为我只是用它来设置innerHTML
。
谢谢。
input = 0.3;
output = input.toFixed(2);
//output: 0.30
使用Number
加上2作为小数位数。
或者,您可以将var array = [0.39, 2.5, 4.25, 5.5, 6.75, 7.75, 8.5], new_array = [];
for(var i = 0, j = array.length; i < j; i++) {
if(typeof array[i] !== 'number') continue;
new_array.push(array[i].toFixed(2));
}
与toFixed
结合使用
Intl.NumberFormat()