JavaScript中的数字百分比

问题描述 投票:18回答:4

给我一个本机(请不要使用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

谢谢。

javascript numbers number-formatting
4个回答
32
投票
input = 0.3;
output = input.toFixed(2);
//output: 0.30

9
投票

您可以在toFixed()对象上使用toFixed()方法:

Number

4
投票

使用Number加上2作为小数位数。


0
投票

或者,您可以将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()
© www.soinside.com 2019 - 2024. All rights reserved.