Precision in Javascript

Something Like that:
0.2 + 0.1

The maximum number of decimals is 17, but floating point arithmetic is not always 100% accurate
For example I want to write number like 0.30000000000000004
0.2 + 0.1

For that you need to create first html code.

HTML

<p id="demo"></p>

After that add this JS code.

JS

var x = 0.2 + 0.1;
document.getElementById("demo").innerHTML = x;

[codepen_embed height=”265″ theme_id=”0″ slug_hash=”Vzvywq” default_tab=”result” user=”pradeepanvi”]See the Pen Precision in Javascript by Pradeep Kumar (@pradeepanvi) on CodePen.[/codepen_embed]

Now you can see

0.30000000000000004

But one thing if we plus 0.2 + 0.1 it should be write 0.3

To solve the problem above, it helps to multiply and divide

After that add this JS code.

JS

var x = (0.2 * 10 + 0.1 * 10) / 10;
document.getElementById("demo").innerHTML = x;

[codepen_embed height=”265″ theme_id=”0″ slug_hash=”RZWxRz” default_tab=”result” user=”pradeepanvi”]See the Pen Precision in Javascript 02 by Pradeep Kumar (@pradeepanvi) on CodePen.[/codepen_embed]

Now you can see

0.3

Leave a Reply

Your email address will not be published. Required fields are marked *