[英]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
使用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.