SwiftiSwift
SwiftiSwift

Reputation: 8747

How to convert a Number to Current Locale in Swift 5

how can I convert a number to current Locale, as some countries are using commas "," instead of periods "."

For example this number:

var number = 1.5

the end result should be this, as commas "," are only allowed in strings:

var number = "1,5"

Upvotes: 0

Views: 984

Answers (1)

matt
matt

Reputation: 535557

This is why there is NumberFormatter. Use it for all user-facing strings that represent numbers. This is an artificial demonstration:

let num = 1.5
let nf = NumberFormatter()
nf.numberStyle = .decimal
nf.locale = Locale(identifier: "en_US")
let s = nf.string(from: num as NSNumber) // 1.5

nf.locale = Locale(identifier: "fr_FR")
let s2 = nf.string(from: num as NSNumber) // 1,5

Why artificial? Because in real life, you do not set the locale of the NumberFormatter. It has the user's locale automatically. Problem solved.

Upvotes: 2

Related Questions