October 17, 2001 - Setting the Number of Decimal Digits | WebReference

October 17, 2001 - Setting the Number of Decimal Digits

Yehuda Shiran October 17, 2001
Setting the Number of Decimal Digits
Tips: October 2001

Yehuda Shiran, Ph.D.
Doc JavaScript

The toFixed(fractionDigits) method formats a number with fractionDigits digits after the decimal place. Suppose:

x = 1234.56789
and you call alert(x.toFixed(4)), you'll get 1234.5679 in IE5.5 and up.

Another way to format a floating number is to multiply it by the proper power of 10, round it to an integer, and then divide it back to the same power of 10. In the above example, you would multiply 1234.56789 by 10,000, get 12345678.9, round it to 12345679, and then divide it by 10,000 to get 1234.5679. Try it.