Javascript面具

时间:2009-10-02 20:11:51

标签: javascript

如何格式化数字以在JavaScript中显示2位小数?

以下内容: 格式(X, “9,999.99”);

4 个答案:

答案 0 :(得分:3)

你应该用这个:

x.toFixed(2);

或者如果你想确定它会起作用:

parseFloat(x).toFixed(2);

答案 1 :(得分:2)

var num = 3.14159;
var fixed = num.toFixed(2);

如果您想要逗号取决于区域设置:

var localed = num.toLocaleString();

粗略地结合:

var num = 3.14159;
var fixed = num.toFixed(2);
var fixednum = parseFloat(fixed);
var localedFixed = fixednum.toLocaleString();

答案 2 :(得分:2)

使用.toFixed(2)

http://www.devguru.com/technologies/javascript/17443.asp

请注意,这将围绕您的号码:

var i = 23.778899;
alert(i.toFixed(2));

给你

23.78

答案 3 :(得分:-1)

我不确定您是要尝试输入还是仅用于在页面上显示文本。如果您尝试格式化输入,可以使用jQuery的蒙版输入插件。

http://digitalbush.com/projects/masked-input-plugin/