0

I am trying to convert text entered by a user (via a UITextField) to a Double, in order to store in Core Data. The issue is that the converted value is incorrect, for example: User Enters: 1.18 Double Value: 1.17999999999999

I have tried a number of different approaches e.g recasting and using the formatter, but the results are the same.

func textFieldDidEndEditing(_ textField: UITextField) {
        print(textField.text) // Prints 1.18

        guard let inputAmount = textField.text else {
            return
        }

        let inputDouble = Utils.doubleFromString(inputAmount)
        print(inputDouble) // Prints 1.18, but is stored as 1.17999999999

        let inputDouble2 = Double(inputAmount)
        print(inputDouble2) // Prints 1.18, but is stored as 1.17999999999

Screenshot in Debug

I can't believe that I am the first person to face this issue but I can't find anything on Stackoverflow - What on earth is going on here? and what can I do to stop it? (storing the 1.179999 and rounding every time I need it seems like a hack)

Any suggestions gratefully received

redPanda
  • 727
  • 7
  • 17
  • Double precision isn't exact. For instance there's no way for a computer to exactly store `0.3` inside a `double`. You're probably hitting that roadblock. [This answer](https://stackoverflow.com/a/753955/1085937) covers it nicely – Jeeter Jul 18 '19 at 20:15
  • If you need it to be exact, you can use a [`Decimal`](https://developer.apple.com/documentation/foundation/decimal). – grooveplex Jul 18 '19 at 20:17
  • Related: [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – vadian Jul 18 '19 at 20:19

0 Answers0