Javascript toPrecision() vs toFixed() – Know the difference

Hey, what’s up coders. Are you learning javascript and wanna know the difference between javascript toPrecision() and toFixed() methods? Read till the last word and soon you will know what is the difference between these two methods. So, let’s begin.

First, let me give you an example of toPrecision() method.

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript toPrecision() Method</h1>


<p id="demoId"></p>

<script>
let x = 8.526;
document.getElementById("demoId").innerHTML = 
  x.toPrecision(2) + "<br>" +
  x.toPrecision(3) + "<br>" +
  x.toPrecision(4);  
</script>

</body>
</html>

Output :

JavaScript toPrecision() Method

8.5
8.53
8.526

Pay attention to the output. You must have noticed something. Here the digit is being counted from the beginning. That means the digits before the decimal point is also being counted here. Like when toPrecision(2) gets called then the output is 8.5. Here the number of digits is two (8 and 5), and that’s what the parameter of the method is. But this is not the case with toFixed.

Now let’s see an example of toFixed() method.

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript toFixed() Method</h1>


<p id="demoId"></p>

<script>
let x = 8.526;
document.getElementById("demoId").innerHTML =
  x.toFixed(1) + "<br>" +
  x.toFixed(2) + "<br>" +
  x.toFixed(3) + "<br>"
</script>

</body>
</html>

Output :

JavaScript toFixed() Method

8.5
8.53
8.526

Notice the digits. Here digits are being counted after the decimal point. Like when toFixed(2) gets called the output is 8.53. The number of digits after the decimal point is 2 and that’s what the parameter of the toFixed() method here is.

So the final point is that toPrecision() count digits from the beginning (Digits before and after the decimal point) whereas toFixed() count digits after decimal point only.

And that ends this post.

Have any question in mind?

Comment below.

Goodbye.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: