swiftnsnumbernsnumberformatternslocalexcode9.2

NSNumberFormatter.number for currency format not working in Device but works in simulator


I've been trying to implement currency format based on passing my custom language identifier.

Below is my code

func currencyFormatter(language:String, amount:String)  -> String  {

    let nsFormatter = NumberFormatter()
    nsFormatter.numberStyle = .currency
    nsFormatter.currencySymbol = ""
    var formattedString: String?
    var amountInNumber:NSNumber!
    if let number = nsFormatter.number(from: amount)
    {
        amountInNumber = number.doubleValue as NSNumber
    }
    nsFormatter.locale = Locale(identifier: language)
    formattedString = ((amountInNumber?.intValue) != nil) ? nsFormatter.string(from: amountInNumber) : amount

    guard let finalString = formattedString else {
        return ""
    }
    return finalString
}

I am trying to pass language as "fr-FR" and amount as "1234.45" then expecting output is "1 234,45".

This is working fine in simulator but not working in device (returning same value 1234.45)

Do i missed anything. Please help!

Thanks in advance


Solution

  • The decimal separator is locale-dependent, therefore parsing "1234.45" fails if the locale's separator is not a period.

    It the input string uses a fixed format with a period as decimal separator then you can set the formatter's locale to "en_US_POSIX" for the conversion from a string to a number. Then set it to the desired locale for the conversion from number to a string.

    Example:

    func currencyFormatter(language: String, amount: String)  -> String  {
    
        let nsFormatter = NumberFormatter()
        nsFormatter.locale = Locale(identifier: "en_US_POSIX")
        nsFormatter.numberStyle = .decimal
    
        guard let number = nsFormatter.number(from: amount) else {
            return amount
        }
    
        nsFormatter.locale = Locale(identifier: language)
        nsFormatter.numberStyle = .currency
    
        return nsFormatter.string(from: number) ?? amount
    }
    
    print(currencyFormatter(language: "fr-FR", amount: "1234.45"))
    // 1 234,45 €