-1

I'm building a calculator app. When I press the % button on the calculator, it multiplies the current value by 0.01.

If I do 52 * 0.01, I'll get 0.52. But if I press it again, it will calculate 0.52 * 0.01, and I get 0.005200000000000001.

This value gets displayed to the user of the app. How do I truncate the extra numbers to end up with 0.0052 so that it makes more sense?

Makoren
  • 321
  • 1
  • 3
  • 12

2 Answers2

0

The answer is to use Decimal instead of Double or Float.

Make sure the calculation is done between Decimals too, meaning you shouldn't try to do a calculation between two Doubles, and cast the result to a Decimal.

Makoren
  • 321
  • 1
  • 3
  • 12
0
let formatterUpperBreakPoint = 999999999.9
let formatterLowerBreakPoint = 0.000000001
let maxInput = 9

let decimalFormatter = NumberFormatter()
decimalFormatter.numberStyle = .decimal
decimalFormatter.groupingSeparator = ","
decimalFormatter.maximumIntegerDigits = maxInput
decimalFormatter.maximumSignificantDigits = maxInput + 1

let number = 0.005200000000000001

if abs(number) < formatterUpperBreakPoint && abs(number) > formatterLowerBreakPoint {
    print(decimalFormatter.string(from: NSNumber(value: number)) ?? "0") // result 0.0052
}