Search code examples
swiftnsnumberformatter

How to format negative 0 with currency NumberFormatter


I noticed my app is displaying "-$0.00" for a value of -0. The simple form of the math is let balance: Double = -1 * value. I want my negative 0 values to just display as "$0.00". Is there a way to have the NumberFormatter properly handle this?

let formatter = NumberFormatter()
formatter.numberStyle = .currency

let d: Double = -1 * 0
formatter.string(from: d as NSNumber)! // -$0.00

Solution

  • If you are working with money, currency etc it is much better to use Decimal than Double and it will also solve your problem here, change the declaration of d as below

    let d: Decimal = -1 * 0
    

    and the formatter will produce "$0.00"