I'm working with a range of number from 0.00 to 9999.99 .
I need to add the "˙" thousands separator, so 1300,00
should became 1˙300,00
.
NSNumberFormatter use "," as separator so it isn't good for me.
I tried using
func formatNumber (i: Float) -> String {
var counter = 0
var correctedNumber = ""
if i > 999 {
for char in "\(i)".characters {
if counter == 1 {
correctedNumber += "˙" + "\(char)"
} else {
correctedNumber += "\(char)"
}
counter++
}
} else {
correctedNumber = "\(i)"
}
return correctedNumber
}
but it can't format decimal numbers.
What's the correct way to do that?
You just need to properly configure the NSNumberFormatter
.
let formatter = NSNumberFormatter()
formatter.groupingSeparator = "˙"
formatter.decimalSeparator = ","
formatter.usesGroupingSeparator = true
formatter.minimumFractionDigits = 2
Testing
formatter.stringFromNumber(1300) // "1˙300,00"
While setting a specific decimalSeparator
and groupingSeparator
certainly works, it's not the best way to do what you want.
NSNumberFormatter
always chooses the format according to the current locale. If the locale is set to English (usually en-US
), then decimal separator will be a ,
and grouping separator a .
.
This way if a user in USA opens the app, they will see number formatted correctly for them. If a user in Europe opens the app, they will also see numbers formatted correctly (as specified by their device settings).
If you really want the app to have one specific number format, you can just set the language explicitly, e.g:
let formatter = NSNumberFormatter()
formatter.locale = NSLocale(localeIdentifier: "it_IT")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With