Reputation: 8033
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
Upvotes: 1
Views: 651
Reputation: 51831
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"
Upvotes: 2
Reputation: 8033
My current approach is:
struct Formatter {
static func currency(_ value: Double) -> String {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
let value = (value == 0) ? 0 : value // Convert -0 to 0
return formatter.string(from: value as NSNumber) ?? ""
}
}
Formatter.currency(-1 * 0) // $0.00
Upvotes: 0