0

I create an array, set the default value is 0.3, according to 0.29999999999999999, why is this so?enter image description here

2
  • 2
    Generally if you need to compare float numbers, don't use Double. You could separate the decimals as Int or just use NSDecimalNumber. Commented Apr 9, 2016 at 5:00
  • Not to be confused with NSDecimal, which you should not use. Commented Apr 9, 2016 at 5:09

2 Answers 2

4

This is because of the binary representation of the floating point values. Some floating point values can not be represented exactly in the given memory space, so they are rounded to a value that fits. Check this post for more details about this. If you want to avoid this most programming languages have a data type that uses base 10 arithmetic and does not have this limitation. For swift that is NSDecimalNumber, but please note that usually this data type is much slower.

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

1 Comment

I understand your meaning, your explanation is very good, thank you very much!
1

It's actually pretty simple. When you have a base 10 system (like ours), it can only express fractions that use a prime factor of the base. The prime factors of 10 are 2 and 5. So 1/2, 1/4, 1/5, 1/8, and 1/10 can all be expressed cleanly because the denominators all use prime factors of 10. In contrast, 1/3, 1/6, and 1/7 are all repeating decimals because their denominators use a prime factor of 3 or 7. In binary (or base 2), the only prime factor is 2. So you can only express fractions cleanly which only contain 2 as a prime factor. In binary, 1/2, 1/4, 1/8 would all be expressed cleanly as decimals. While, 1/5 or 1/10 would be repeating decimals. So 0.1 and 0.2 (1/10 and 1/5) while clean decimals in a base 10 system, are repeating decimals in the base 2 system the computer is operating in. When you do math on these repeating decimals, you end up with leftovers which carry over when you convert the computer's base 2 (binary) number into a more human readable base 10 number.

more details:

http://0.30000000000000004.com/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.