1

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

3
  • NSNumberFormatter has many properties to control the output format. Did you try setting minimumFractionDigits/maximumFractionDigits ? Commented Mar 10, 2015 at 7:51
  • Yes it was actually what I was looking for and couldn't find the keyword "fraction". Thanks. Commented Mar 10, 2015 at 8:09
  • stackoverflow.com/a/27932153/2303865 Commented Mar 10, 2015 at 8:43

1 Answer 1

8

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)
Sign up to request clarification or add additional context in comments.

2 Comments

NSNumberFormatter has renamed to NumberFormatter in swift 4
@Johnny: You are right (and actually already in Swift 3), thanks for the notice!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.