将数字格式化为两位小数 [英] Format a number to two decimal places

查看:47
本文介绍了将数字格式化为两位小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给我一​​个原生的(请不要使用 jQuery、Prototype 等)JavaScript 函数来转换数字,如下所示:

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

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

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

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

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

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

谢谢.

推荐答案

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

这篇关于将数字格式化为两位小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆