Jump to content

Small mistake in the tutorial


kirby555
 Share

Recommended Posts

Good afternoon admin,

 

This morning I try to learn the Javascript through the tutorial, I found some small mistake in this tutorial.

 

JavaScript > JS Numbers > under Precision section

 

W3School%20-%20Mistake.jpg

 

<script>
function myFunction() {
x = (0.2*10 + 0.1*10) / 10;
document.getElementById("demo").innerHTML = "0.2 + 0.3 = " + x;
}
</script>
The output will be: 0.2 + 0.3 = 0.3
Tutorial Link:
http://www.w3schools.com/js/tryit.asp?filename=tryjs_inaccurate3
Link to comment
Share on other sites

Well, as an example that one is pretty horrible anyway, even without the error. I think what they were hinting at is valid in that you can multiply dollars by 100 to create cents and then work in whole cents until you get to the final result and then divide by 100 and use toFixed(2) to achieve an accurate result.

Link to comment
Share on other sites

Their solution is a decent one.

Floating point operations can often give you results like 0.40000000000001 or 0.99999999999998 for apparently no reason.

 

By multiplying and dividing you can avoid that problem.

console.log(0.1 + 0.2); // Shows 0.30000000000000004console.log( (0.1 * 10 + 0.2 * 10) / 10 ); // Shows 0.3
Link to comment
Share on other sites

a more in-depth explaination on Floating point calculationshttps://www.youtube.com/watch?v=PZRI1IfStY0

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...