0

I am trying to round a number to 7 decimal places by converting my input number to a string and then back to a double. The value of the string is how I would like it, but when converting it back to a double more decimal places are revealed. Any remedy for this situation?

let inputNumber: Double = 99.99990338164251

let roundedString = String(format: "%.7f", inputNumber) //"99.9999034"

let outputNumber = Double(roundedString) //99.99990339999999
  • You can use NSNumberFormatter when displaying your float to the user. If you need more precision you can use Swift Decimal type – Leo Dabus Mar 15 '20 at 23:43

1 Answers1

0

Use Decimal class instead of Double https://developer.apple.com/documentation/foundation/decimal

You problem is a common for floating number calculations

More detailed for ObjC class https://developer.apple.com/documentation/foundation/nsdecimalnumber

Vyacheslav
  • 26,359
  • 19
  • 112
  • 194