Search code examples
swiftcurrencynumber-formatting

Format Double for negative currency, or remove "-" sign from Double


I have a Double which can be positive or negative that I want to display in the following way:

For positive values:

+$1.10

For negative values:

-$0.50

And blank for 0 values

I've tried like this:

Double surcharge = ...
if(surcharge < 0){
    cell.lblSurcharge.text = "-$" + String(format:"%.02f", surcharge)
}else if(surcharge > 0){
    cell.lblSurcharge.text = "+$" + String(format:"%.02f", surcharge)
}else{
    cell.lblSurcharge.text = nil
}

but for negative values it shows them like this:

-$-0.50

How can I format it correctly, or remove the "-" from the Double?


Solution

  • You know that surcharge is negative at that point, so just add - to make it positive for the formatting. Also, you can move the "-$" into the format string:

    Change:

    cell.lblSurcharge.text = "-$" + String(format:"%.02f", surcharge)
    

    to:

    cell.lblSurcharge.text = String(format:"-$%.02f", -surcharge)
    

    To do it all in one line, use the trinary operator (?:) to handle zero and to add the sign to the format string:

    cell.lblSurcharge.text = surcharge == 0 ? "" : String(format:"%@$%.02f", surcharge > 0 ? "+" : "-", abs(surcharge))