Search code examples
swiftnumber-formatting

How to show zero after comma in NumberFormatter


I try format my number to string use NumberFormatter. This is my code:

        let formater = NumberFormatter()
        formater.groupingSeparator = " "
        formater.numberStyle = .decimal


        let formattedNumber = formater.string(from: (self.money as NSNumber))

        self.currentMoneyLabel.text = "\(formattedNumber!) ₽"

i have number something like this 1 234 but i need get number something like this 1 234,00.

if my number is after the decimal point the number is not zero everything works well. But if the number after the comma is zero, it does not display it. How to make the numbers up to hundredths always displayed, even if it is zero?


Solution

  • Just add:

    formater.minimumFractionDigits = 2
    

    Documentation is here: https://developer.apple.com/documentation/foundation/numberformatter/1410459-minimumfractiondigits

    EDIT: But you should use currency format with the correct locale:

    let price = 1234
    
    let formatter = NumberFormatter()
    formatter.numberStyle = .currency
    formatter.locale = Locale(identifier: "ru_RU")
    formatter.string(for: price) // "1 234,00 ₽"
    

    But if you prefer that your app adapts to the locale of the device, just replace the locale line by:

    formatter.locale = .current