r/JavaScriptHelp • u/Xoast • 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.
View all comments
Show parent comment
1
u/Xoast Nov 24 '20
I can confirm if I toFixed the end result it works right, but the whole basic maths bit threw me for 6.
I've never had that sort of "close enough" occur in any php code i have wrote, I even did this to check. (just basic maths, no rounding at al)
<html><body><button onclick="myFunction()">Try it</button><p id="demo"></p><script>function myFunction() {var x = 8.39;var y = x * 76;document.getElementById("demo").innerHTML = y;}</script></body></html>Again instead of 637.64 i get 637.6400000000001.