How to format a float in javascript?

In JavaScript, when converting from a float to a string, how can I get just 2 digits after the decimal point? For example, 0.34 instead of 0.3445434.



There are functions to round numbers. For example:

var x = 5.0364342423;
print(x.toFixed(2));

will print 5.04.

EDIT: Fiddle


Be careful when using toFixed() :

First, rounding the number is done using the binary representation of the number, which might lead to unexpected behaviour. For example

(0.595).toFixed(2) === '0.59'

instead of '0.6' .

Second, there's an IE bug with toFixed() . In IE (at least up to version 7, didn't check IE8), the following holds true:

(0.9).toFixed(0) === '0'

It might be a good idea to follow kkyy's suggestion or to use a custom toFixed() function, eg

function toFixed(value, precision) {
    var power = Math.pow(10, precision || 0);
    return String(Math.round(value * power) / power);
}
链接地址: http://www.djcxy.com/p/27466.html

上一篇: 如何使用apache tez在hadoop纱线集群上运行mapCreduce作业?

下一篇: 如何在JavaScript中格式化一个浮点数?