Formatting values with Numberformatter() Swift

Asked

Viewed 127 times

0

I have a function that I want to format the values to decimals with the Brazilian standard. Today my function is like this ...

func formatNumberToDecimal(value:Double) -> String {
        let numberFormatter = NumberFormatter()
        numberFormatter.numberStyle = NumberFormatter.Style.decimal
        numberFormatter.groupingSeparator = "."
        return numberFormatter.string(from: NSNumber(value:defaultValue)) ?? "Valor indefinido"
}

But it returns with a value in the format EN for example:

formatNumberToDecimal(1000.00)
// retorna o valor -> 1.000,00

I wonder how I can turn to en with two houses after the comma. In the example above it should return 1,000.00

1 answer

1


The class NumberFormatter has a property locale, that can be assigned to customize the Locale used as a basis in number formatting.

According to your documentation, Locale is a class that has linguistic, cultural and technological conventions that should be used to format values for display.

This way, you can assign the desired locale in the instance of NumberFormatter you are using, and do the following to get the correct formatting for "pt_BR", as you wish:

func formatNumberToDecimal(value:Double) -> String {
    let numberFormatter = NumberFormatter()

    // Atribuindo o locale desejado
    numberFormatter.locale = Locale(identifier: "pt_BR")

    // Importante para que sejam exibidas as duas casas após a vírgula
    numberFormatter.minimumFractionDigits = 2 

    numberFormatter.numberStyle = .decimal

    return numberFormatter.string(from: NSNumber(value:value)) ?? "Valor indefinido"
}
  • Formatter has a method called string(for: Any) that Voce can pass a Double straight to it. No need to create an Nsnumber object numberFormatter.string(for: value) ?? "Valor indefinido"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.