4

I can't figure out the reason 100000000000000030/10 = 10000000000000004 in JavaScript, I haven't seen this problem in other questions.

  <script>
    alert(100000000000000030/10);
  </script>

12
  • 1
    Just curious: in which context are you using this calculation? Because that's a really big number. Can you show us the code around it please? Commented Dec 14, 2018 at 19:44
  • 1
    "Computer math is to math what computer music is to music." Maybe write some code that demonstrates this question. Without a minimal reproducible example this question isn't complete. Commented Dec 14, 2018 at 19:44
  • 3
    Javascript uses double-precision floating point for numbers. You're bound to encounter some anomalies like this. Commented Dec 14, 2018 at 19:44
  • There are JS math libraries out there which remove most of the inaccuracies and limits (e.g max number). I wouldn't recommend to use vanilla JS for math that requires absolute precision. Commented Dec 14, 2018 at 19:48
  • You also get the wrong result for 100000000000000030 + 1 or 100000000000000030 - 1. Or try 100000000000000030 + 9 for more fun. Commented Dec 14, 2018 at 19:48

1 Answer 1

4

Before doing this calculation you may want to know that whether this number is a safe javascript number or not. you can use - Number.isSafeInteger(100000000000000030), to know that.

"The MAX_SAFE_INTEGER constant has a value of 9007199254740991 (9,007,199,254,740,991 or ~9 quadrillion). The reasoning behind that number is that JavaScript uses double-precision floating-point format numbers as specified in IEEE 754 and can only safely represent numbers between -(253 - 1) and 253 - 1."

You may also want to read more here - Division and remainder of large numbers in JavaScript

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.