Javascript 将数字格式化为两位小数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4610298/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 13:15:44  来源:igfitidea点击:

Format a number to two decimal places

javascriptnumbersnumber-formatting

提问by ma11hew28

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

给我一个原生的(请不要使用 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

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

例如,在 Ruby 中,我会做这样的事情:

>> 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.

输出可以是数字或字符串。我真的不在乎,因为我只是用它来设置innerHTML.

Thank you.

谢谢你。

回答by Eric Fortis

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

回答by Jacob Relkin

You can use the toFixed()method on Numberobjects:

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

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

回答by Jacob

Use toFixedwith 2 as the number of decimal places.

使用toFixed2 作为小数位数。

回答by StangSpree

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

或者您可以使用Intl.NumberFormat(){ 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);