mergesort mergesort - 3 months ago 11
Swift Question

How can I format currency depending on decimal value?

I am using

NSDecimalNumber
to format currency and want the following inputs and outputs:

9.99 --> 9.99

10 --> 10

10.00 --> 10

9.90 --> 9.90

9.9 --> 9.90

0 --> 0

0.01 --> 0.01

20 --> 20

10.01 --> 10.01


How can I do this in Swift.

EDIT: Essentially if there are cents (i.e. cents > 0) then display the cents. Otherwise, don't.

Answer

Your rule is "Display two fractional digits if either is non-zero; otherwise, display no fractional digits and no decimal point”. I would do it in the most straightforward way:

let number = NSDecimalNumber(string: "12345.00")
let formatter = NSNumberFormatter()
formatter.positiveFormat = "0.00"
let formattedString = formatter.stringFromNumber(number)!
    .stringByReplacingOccurrencesOfString(".00", withString: "")
Comments