I have the following Float: 1123455432.67899
My desired result is a String: 1,123,455,432.67899
Best case correct ,
and .
based on location (US/Europe)
struct Number {
static let withSeparator: NumberFormatter = {
let formatter = NumberFormatter()
formatter.groupingSeparator = ","
formatter.numberStyle = .decimal
return formatter
}()
}
let myFloat: Float = 1123455432.67899
let myNumber = NSNumber(value: myFloat)
let formatter = Number.withSeparator
if let result = formatter.string(from: myNumber) {
print(result)
}
This formatter works great as long as my Float has no decimals, als soon as I'm having decimals it starts to "calculate". It calculates up/down based on the 3rd decimal number.
What am I missing? What's the best way to get a String: 1,123,455,432.67899
from a Float
with no matter how many decimal numbers? Help is very appreciated.
Edit:
My exact function:
func formatValue(_ value: String ) -> String {
if let double = Double(value) {
let formatter = Number.withSeparator
if let result = formatter.string(from: NSNumber(value: double)) {
return result
} else {
return value
}
} else {
return value
}
}
value
is always a number for example 5.5555555555
. But in this specific case the result = 5.556
.