0

Trying to convert string to decimal and shows unexpected values for some strings such as 8.80 and 9.80 , tried to run some code in playground and Xcode, please refer below screen shots. I suspect this as a apple bug, Any suggestions why does the Double append zeros to some values ?

Also i have noticed using print you get expected value, but the variable is actually holding the big value with appended zeros, please refer screen shot, I still consider this as a bug.

var totalStr = "8.80"
var total = Double(totalStr)

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

Max
  • 5,380
  • 6
  • 42
  • 66
  • http://stackoverflow.com/questions/21895756/why-are-floating-point-numbers-inaccurate – luk2302 Dec 08 '16 at 11:40
  • Are you doing something money related? If so: do NOT use floating point numbers. – luk2302 Dec 08 '16 at 11:41
  • @luk2302 yes what would be right type to use ? – Max Dec 08 '16 at 11:43
  • Integers! Or some loss-less data structure. Floating point is lossy. – luk2302 Dec 08 '16 at 11:44
  • (NS)DecimalNumber is another option. – Martin R Dec 08 '16 at 11:54
  • @MartinR i dont see a proper answer what needs to be done when you run into such situations, I did refer to the post you marked duplicate of and most of the answers are not correct or too complicated and not even marked as answer . Would you like to check proper answer for this. – Max Dec 08 '16 at 11:58
  • 1
    You asked why `Double(totalStr)` prints as `"8.8000000000000001"` and that *is* answered in the linked to Q&A. @luk2302 also provided a link which explains the general problem. Another one is http://stackoverflow.com/questions/588004/is-floating-point-math-broken. `Double` is a *binary* floating point number and that cannot represent the value `8.8` exactly. It is definitely not a Apple bug. – Martin R Dec 08 '16 at 12:03
  • Here is another one: http://stackoverflow.com/questions/37794622/round-issue-in-swift. – Martin R Dec 08 '16 at 12:08
  • @MartinR I am a bit confused had a look at your link, they are suggesting to us NSDecimalNumber, But when i use NSDecimal number i don't see any convincing results.I have attached the screen shot to the question now. – Max Dec 09 '16 at 11:52
  • That is a flaw in the Playground (which apparently uses `.doubleValue` for display). Try `let totalString = "9.8"; print(NSDecimalNumber(string: totalString))` in a compiled project, or `NSDecimalNumber(string: totalString).decimalValue` in the Playground. – Martin R Dec 09 '16 at 11:57
  • I tried your suggestions, I see that when I print in xCode project I get right value but the variable still holds the big value and does not solve the problem by using .doubleValue or NSDecimalNumber , Any Suggestions, I think its time to mark this as a question and not duplicate. Please refer my screen shot. – Max Dec 09 '16 at 13:49

0 Answers0