How to convert number formate with separated by ,
Example Resultant String
"38963.26" value into "38,863.26"
"1013321.22" Value into "10,13,321.22"
//MARK:- Seperator number formate 1000 - 1,000
extension Formatter {
static let withSeparator: NumberFormatter = {
let formatter = NumberFormatter()
formatter.groupingSeparator = ","
formatter.numberStyle = .decimal
return formatter
}()
}
extension BinaryFloatingPoint {
var formattedWithSeparator: String {
return Formatter.withSeparator.string(for: self) ?? ""
}
}
let resultValue = StringValue.CGFloatValue()?.formattedWithSeparator
print("Resultant", resultValue!)
CGFloatVaule default method for converting String to floatValue. same like String.floatValue.
For value "38963.26" is gives resultant value "38,963.262" I wonder why its like that extra 2 in decimal.
print("38963.26".CGFloatValue()!.formattedWithSeparator)
Output "38,863.262"
Either set a proper (that uses this style for formatting) locale or set both decimal and grouping separator on your formatter instance since not all Locale might use the same separators.
Then you also need to set max number of fraction digits if you are using float (for some reason this isn't needed for Double
)
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.locale = Locale(identifier: "en_US")
formatter.maximumFractionDigits = 2
if let str = formatter.string(for: Float(numberString)) {
print(str)
}
let formatter = NumberFormatter()
formatter.groupingSeparator = ","
formatter.decimalSeparator = "."
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 2
if let str = formatter.string(for: Float(numberString)) {
print(str)
}
Both yields
38,963.26