Difference Between toFixed() and toPrecision() in JavaScript

Introduction

JavaScript provides two methods: toFixed() and toPrecision() to precisely a number to get an accurate value. It is mainly used in financial data or scientific data to get more accuracy. For example, if a decimal number is 5.567, and we need to be precise up to 2 decimal digits, the precise value will be 5.57.

Here we will discuss the two methods and the differences between them.

toFixed() Method in JavaScript

The toFixed() method converts a number into a string, keeping a specified number of decimals.

Syntax

number.toFixed(n)

Here the number is variable, and n is the optional parameter of number type which helps to get an accurate number.

toPrecision() method in JavaScript

The toPrecision() method formats a number to a specified length. It returns all digits(as per parameter value), excluding decimal points. Suppose the number is 3.576, and you use precise up to 2; then the value will be 3.6.

Syntax 

number.toPrecision(n)

Here the 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(); // 6  
var b = num.toFixed(2); // 5.57  
var c = num.toFixed(10); // 5.5678900000  
  
var a1 = num.toPrecision(); // 5.56789  
var b1 = num.toPrecision(2); // 5.6  
var c1 = num.toPrecision(10); // 5.567890000  

Case 1

Without any parameter toFixed() returns all digits before the decimal point with precise, and toPrecision() returns the whole number. Compare variables a and a1 in the preceding example.

Case 2

toFixed() returns digits before the decimal point, including digits(as per parameter) after the decimal point, but toPrecision() returns digits(as per parameter) before the decimal and after the decimal point. The difference is that the toFixed() count starts after a decimal point, but the toPrecision() count starts before the decimal point. Compare the value of variables b and b1.

Case 3

In this case, the parameter value(10) exceeds no. of digits after the decimal point, so adding an extra "0" is necessary to make it precise. Both toFixed() and toPrecision() add an extra 0 to make it precise; the only difference is no digits after the decimal point. toFixed() adds 5 zeros but toPrecision() adds 4 zeros. Compare the value of variables c and c1.

I hope this blog helps you to understand the difference between toFixed() and toPrecision() in JavaScript.

Happy Coding!!