JavaScript provides two methods toFixed() and toPrecision() precise a number to get accurate value. It is mostly used in financial data or scientific data to get more accuracy. For example, a decimal number 5.567 and we need to precise upto 2 decimal digit then precise value will be 5.57.
Here we will discuss about the two methods and difference between them.
toFixed()
The toFixed() method converts a number into a string, keeping specified number of decimals.
Syntax
number.toFixed(n)
Here number is variable and n is the optional parameter of number type which helps to get accurate number.
toPrecision()
The toPrecision() method formats a number to a specified length. It returns all digits(as per parameter value) excluding decimal point. Suppose number is 3.576 and you use precise upto 2 then value will be 3.6.
Syntax:
number.toPrecision(n)
Here number is variable and n is the optional parameter of number type which helps to precise the number.
Analysis
- var num = 5.56789;
-
- var a = num.toFixed();
- var b = num.toFixed(2);
- var c = num.toFixed(10);
-
- var a1 = num.toPrecision();
- var b1 = num.toPrecision(2);
- var c1 = num.toPrecision(10);
Case 1
Without any parameter toFixed() returns all digits before decimal point with precise and toPrecision() returns whole number. Compare variable a and a1 in the preceding example.
Case 2
toFixed() returns digits before decimal point including digits(as per parameter) after decimal point but toPrecision() returns digits(as per parameter) before decimal and after decimal point. Difference is toFixed() count starts after decimal point but toPrecision() count starts before decimal point. Compare value of variable b and b1.
Case 3
In this case parameter value(10) exceeds no. of digits after decimal point so adding extra "0" to make it precise. Both toFixed() and toPrecision() add extra 0 to make it precise, the only difference is no of digits after decimal point. toFixed() adds 5 zeros but toPrecision() adds 4 zeros. Compare value of variable c and c1.
Hope this blog helps you to understand the difference between toFixed() and toPrecision() in JavaScript.
Happy Coding!!