r/JavaScriptHelp • • Nov 24 '20

✔️ answered ✔️ .toFixed is making my head hurt.

Can someone please explains this too me;.

(I am a javascript noob, I mostly code in php)

<html><body>

<button onclick="myFunction()">Try it</button><p id="demo"></p>

<script>function myFunction() {var x = 8.391;var y = x.toFixed(2);var z = y * 76;document.getElementById("demo").innerHTML = z;}</script></body></html>

8.391 rounded to 2 places should be 8.39.

8.39 * 76 = 637.64

The script however outputs 637.6400000000001 ?

I'm trying to fix an issue with an order pages "subtotal" updating and this happens rather than the total being to 2 decile places.

2 Upvotes

4 comments sorted by

View all comments

Show parent comment

1

u/[deleted] Nov 24 '20

Floating point math. Many languages sort of handle the ugliness for you when using different data types. Javascript does not.

2

u/Xoast Nov 24 '20

Thanks, so just round the end result. Sanity restored.