Format a number to two decimal places

时光毁灭记忆、已成空白 提交于 2020-05-10 07:29:49

问题


Give me a native (no jQuery, Prototype, etc. please) JavaScript function that converts numbers as follows:

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

E.g., in Ruby, I'd do something like this:

>> sprintf("%.2f", 2.5)
=> "2.50"

The output may be a number or a string. I don't really care because I'm just using it to set innerHTML.

Thank you.


回答1:


input = 0.3;
output = input.toFixed(2);
//output: 0.30



回答2:


You can use the toFixed() method on Number objects:

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));
}



回答3:


Use toFixed with 2 as the number of decimal places.




回答4:


Alternatively you can use Intl.NumberFormat() with { style: 'percent'}

var num = 25;

var option = {
  style: 'percent'

};
var formatter = new Intl.NumberFormat("en-US", option);
var percentFormat = formatter.format(num / 100);
console.log(percentFormat);


来源:https://stackoverflow.com/questions/4610298/format-a-number-to-two-decimal-places

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!