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
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