O'Reilly logo

JavaScript & DHTML Cookbook by Danny Goodman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Formatting Numbers for Text Display

NN 2, IE 3

Problem

You want to display the results of numeric calculations with a fixed number of digits to the right of the decimal.

Solution

Two recent additions to the JavaScript language (and ECMA standard) simplify the display of numbers with a specific number of digits. These methods are implemented in IE 5.5 or later for Windows and Netscape 6 or later. To obtain a string containing a number with digits to the right of the decimal, use the toFixed( ) method, as in the following:

document.myForm.total.value = someNumber.toFixed(2);

The argument to the toFixed( ) method is the number of digits to the right of the decimal. Even if the number is an integer, the resulting string has a decimal and two zeros to the right of the decimal.

To obtain a string containing a number with a total fixed number of digits, use the toPrecision( ) method, as in the following:

document.myForm.rate.value = someNumber.toPrecision(5);

The argument to the toPrecision( ) method is the total number of digits in the returned string value, including digits to the left and right of the decimal (the decimal is not counted). If the original value has fewer digits than the method argument calls for, the result is padded with zeros to the right of the decimal:

var num = 98.6;
var preciseNum = num.toPrecision(5);          // preciseNum is now 98.600

For older browsers, number formatting is a more cumbersome process, but one that can be encapsulated in the formatNumber( ) utility function ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required