Nico
Nico

Reputation: 6359

How to format a decimal number (double) to a string with a certain precision and based of the default Locale?

So far I was formatting my doubles into Strings like this:

String(format:"%0.4f", rate)

Problem: the decimal separator is always . while in France for example we use ,

Then I used an NSNumberFormatter with numberStyle = .DecimalStyle but then I cannot choose the precision of 4 digits as I did before.

What are my solutions?

Thanks

Upvotes: 1

Views: 3140

Answers (1)

Martin R
Martin R

Reputation: 539925

Use a NSNumberFormatter and set both the minimum and maximum fraction digits to use:

let fmt = NSNumberFormatter()
fmt.maximumFractionDigits = 4
fmt.minimumFractionDigits = 4
let output = fmt.stringFromNumber(123.123456789)!
println(output) // 123,1235 (for the German locale)

Update for Swift 3 (and later):

let fmt = NumberFormatter()
fmt.maximumFractionDigits = 4
fmt.minimumFractionDigits = 4
let output = fmt.string(from: 123.123456789)!
print(output) // 123,1235 (for the German locale)

Upvotes: 8

Related Questions