简体   繁体   English

将数字格式化为两位小数

[英]Format a number to two decimal places

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

Eg, 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.谢谢。

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

You can use the toFixed() method on Number objects:您可以在Number对象上使用toFixed()方法:

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 2 作为小数位数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM