0
let formatter = NumberFormatter()
let sample1 = formatter.number(from: "29.99") ---> 29.99
let sample2 = formatter.number(from: "79.99") ---> 79.98999999999999

But I expect to get 79.99 as the result of sample2

Tried using different rounding modes with no help

Coder
  • 3
  • 2
  • 1
    Related: [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – vadian Mar 07 '23 at 10:40

1 Answers1

0

This happens because a Floating Point Number. You can see what is FPN in here

If you need 2 decimal value with round , you can use this extension link

extension NSNumber {
    func rounded(to decimalPlaces: Int) -> Double {
        let multiplier = pow(10, Double(decimalPlaces))

    return (Double(truncating: self) * multiplier).rounded(.toNearestOrEven) / multiplier
    }
}

  let sample1 = formatter.number(from: "29.99")?.rounded(to: 2) --> will be Optional(29.99)
  let sample2 = formatter.number(from: "79.99")?.rounded(to: 2) --> will be Optional(79.99)
Omer Tekbiyik
  • 4,255
  • 1
  • 15
  • 27