JavaScript offers a wide range of functions and methods to work with numeric values. One of them is the toFixed()
method which converts a number into a string and rounds it if needed.
The syntax of this method is easy, you can call it using a number. For example:
num = 1340.54;
console.log(num.toFixed()); // logs 1341
This method has one optional parameter. It’s a number that determines an amount of digits after the decimal point. If you don’t pass any arguments, toFixed()
will use 0 by default. At the same time, if you pass a number that exceeds the actual amount of signs after dot, the function will add zeros to match the specified requirement.
The following code illustrates different cases of using the toFixed()
method:
num = 1340.5436;
console.log(num.toFixed()); // logs 1341
console.log(num.toFixed(2)); // logs 1340.54
console.log(num.toFixed(6)); // logs 1340.54360
Notes on toFixed() method
The argument to pass must be less than 100 (this may differ depending on the version, in some cases the maximum value might be 20) and of course passing a negative number will lead to a Range Error
message.
The method accepts floating-point values but strings are not allowed. By the way, if you try to use toFixed() with something other than a number (a string, for example), a Type Error message will be shown.
num = '1340.5436';
console.log(num.toFixed()); // TypeError: num.toFixed is not a function
In case your number is bigger than 1e+21, the method will just call toString()
and return the string representation of this number. Below you can see the difference between the two examples.
num1 = 1e+20;
console.log(num1.toFixed(2)); // logs 100000000000000000000.00
num2 = 1e+21;
console.log(num2.toFixed(2)); // logs 1e+21
Keep in mind certain features of toFixed()
related to literals. If your number does not have any digits after the point, you need to surround it by parentheses or put an additional point to avoid Syntax Error
. It happens because an interpreter considers your literal as a regular number with a floating-point and when it finds not digits but letters after the point, it brings the error.
In case you call this method using a negative numeric literal, you will get a number instead of a string returned. In order to avoid it you need to use parentheses as well. The following code illustrates these rules.
console.log((167).toFixed(2)); // logs 167.00
console.log(165.222435.toFixed(2)); // logs 165.22
console.log(typeof(-167.45.toFixed(2))); // logs "number"
console.log(typeof((-167.45).toFixed(2))); // logs "string"
Note that you can easily call toFixed()
using variables or literals even though they are primitives which typically don’t have any methods or properties. However, JavaScript automatically wraps them into the Number object in order to make the method execution possible. This concept is called “autoboxing” and is very helpful in various situations.
Possible mistakes
Sometimes, execution of the toFixed()
method may lead to unexpected results. For example, if you try to round 1.175 to the nearest hundredth, the function will return 1.18. At the same time performing this operation with 4.175 will result in 4.17.
console.log((1.175).toFixed(2)); // logs 1.18
console.log((4.175).toFixed(2)); // logs 4.17
The reason for this confusion lies in the way the numbers are encoded. JavaScript stores float numbers according to The IEEE Standard for Floating-Point Arithmetic (IEEE 754). That’s why the numbers representation in this format may be different from what we got used to.
Another possible mistake is rounding down instead of up. For example, let’s call this method using a literal of -2.005 and round it to two digits after the point. The expected result is -2.01 however it returns -2.00 instead.
console.log((2.005).toFixed(2)); // logs 2.00
toFixed() and alternatives
While working with currency, toFixed()
is very convenient. For example, if you want to store and represent the price of some product which is 34.50, you can assign this value to a variable and pass it as an argument but 34.5 will be printed in the console instead. The use of toFixed()
can help you to gain your goal in this case which is shown in the following code.
price = 34.50;
console.log(price); // logs 34.5
console.log(price.toFixed(2)); // logs 34.50
At the same time the use of toFixed()
for rounding of some specific numbers may lead to unexpected results so in some cases you may need to replace it with an alternate Math.round()
function. In the following code you can see the implementation of this method for rounding floating-point numbers.
function round(number, digits) {
return Number(Math.round(number +'e'+ digits) +'e-'+ digits);
}
console.log(round(2.005,2)); // logs.2.01
There are some other functions from the Math
class that allow simple rounding of numbers in various ways. For example, Math.floor()
performs rounding down (will return 35 for 35.9 and -5 for -4.6), Math.ceil()
rounds the numbers up (will return 24 for 23.4 and -2 for -2.8) and Math.trunc()
removes all digits after the point. All of them are illustrated in the example below.
console.log(Math.floor(-4.6)); // logs -5
console.log(Math.ceil(-2.8)); // logs -2
console.log(Math.trunc(-4.6)); // logs -4
Summary
To sum up, JavaScript provides a simple toFixed()
method which allows you not only to convert the number into a string but also round it to as many digits after a point as you wish. You can easily use this method with primitives because of the JS autoboxing technique.
However, due to IEEE 754 format of number storing, the results returned by toFixed() might be a bit unexpected sometimes, so there are several other ways to round numbers in JavaScript. The use of Math.round()
is one of them. At the same time, toFixed() is very convenient while there is a need to work with currency or represent some money values.