'Swift show price depends on Locale

I am getting a string value that represents a price. I want to convert it to another string with specific precision and format it according to a current device Locale.

Decimal(string: "123,4567", locale: NSLocale.current)?.formatted(.number.precision(.fractionLength(precision)))

This code works for the german language and the output is "123,45". But if I switch to English the output is "123.00". The problem is with the dot instead of the comma. Any ideas how to fix it and show the correct number "123.45"?



Solution 1:[1]

The locale used for the input string must match the format of the string, so if it is a German format then use a German locale

let locale = Locale(identifier: "de_DE")
let string = Decimal(string: "123,4567", locale: locale)?
    .formatted(.number.precision(.fractionLength(precision)))

This uses Locale.current (Swedish in this example) for the output

123,46

Since this is a price here is a currency example

let string = Decimal(string: "123,4567", locale: .current)?
    .formatted(.currency(code: "EUR")
        .precision(.fractionLength(2))
        .rounded(rule: .down)
        .locale(.current))

€123,45

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Joakim Danielson