JavaScript toFixed() Method
This tutorial covers the toFixed() method, from JavaScript's Number object. The toFixed() method returns a string representation of a number, determining post-decimal precision based on the argument passed. If no argument is passed, the toFixed() method behaves as though zero was passed; if the argument passed exceeds 20, a call to the Number.toString() method will be made instead.
The toFixed() method only takes into account digits following the decimal point, regardless of those preceding it. To control the precision of all digits, both before and after the decimal point, you should instead use the Number object's toPrecision() method.
Using the toFixed() Method without Argument
When no argument is passed to the toFixed() method, it will assume that a precision of zero was requested (no digits after the decimal point.) Remember that the toFixed() method returns a string, not a number.
var numex = 3.49;
alert( numex.toFixed() );
Since no argument equates requesting a zero post-decimal precision, all digits following the decimal were truncated: our number was in effect rounded down.
The script above returned the same result as numex.toFixed(0)
would have. To illustrate the number rounding performed by the toFixed() method, the script below assigns a slightly higher value to our numerical variable.
var numex = 3.5;
alert( numex.toFixed(0) ); // Same as passing no argument
This time, JavaScript rounded up our number:
Using the toFixed() method without argument, or by passing zero as precision argument, amounts to the same as extracting an integer, for which the parseInt() function might be a clearer choice.
Using the toFixed() Method with an Argument
The number passed as argument to the toFixed() method will determine the number of digits visible after the decimal point. If called on an integer (a round number), toFixed() will pad the returned value with zeros as needed.
var numex = 4;
alert( numex.toFixed(3) );
The toFixed() method returned a floating point form of the number 4, as a string. Notice that three zeros follow the decimal point:
Let us know limit the number of digits following the decimal point by passing a restrictive number to the toFixed() method (a number smaller than the current number of digits after the decimal point).
var numex = 3.1415926535;
alert( numex.toFixed(5) );
Our script now limited the number of digits appearing after the decimal point:
Test the Number.toFixed() Method
Interactively test the Number.toFixed() method by editing the JavaScript code below and clicking the Test Number.toFixed() method button.
Browser support for JavaScript Number toFixed() method | |||
---|---|---|---|