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
Format a number to two decimal places
提问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
回答by Jacob
Use toFixed
with 2 as the number of decimal places.
使用toFixed
2 作为小数位数。
回答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);