1

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?

1 Answer 1

5

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
2
  • 1
    Use string(for:) to avoid the need for NSNumber.
    – Sulthan
    Mar 1, 2019 at 11:11
  • Indeed, I simply copy and paste his original code. I edited my answer, thanks.
    – Zaphod
    Mar 1, 2019 at 11:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.