Reputation: 569
I have a question about add thousand separator.
I have three type of number string.
I find the answer in stack here.
But I try to use it, and failed to add thousand separator.
Have any idea to me? Thanks.
let str = "1000"
let string1 = "5000.000"
let string2 = "2000.0"
let convertStr = str.formattedWithSeparator //in playground, get error 「Value of type 'String' has no member 'formattedWithSeparator'」.
let convertStr1 = Float(string1)!.formattedWithSeparator //get error too.
let convertStr2 = Float(string2)!.formattedWithSeparator //get error too.
extension Formatter {
static let withSeparator: NumberFormatter = {
let formatter = NumberFormatter()
formatter.groupingSeparator = ","
formatter.numberStyle = .decimal
return formatter
}()
}
extension BinaryInteger {
var formattedWithSeparator: String {
return Formatter.withSeparator.string(for: self) ?? ""
}
}
Upvotes: 3
Views: 245
Reputation: 313
You can use this method
func currencyMaker(price: NSNumber) -> String {
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = NumberFormatter.Style.decimal
numberFormatter.groupingSeparator = ","
let formattedNumber = numberFormatter.string(from: price)
return formattedNumber!
}
like this :
let myNumber1 = currencyMaker(price: 2000)
let myNumber2 = currencyMaker(price: 5983223)
the print is :
print(myNumber1) // 2,000
print(myNumber2) // 5,983,223
Upvotes: 0
Reputation: 535945
Number formatters do not start with a "number string"; they start with a number. Thus, for example, using the Formatter extension code you already have:
let n = 5000
let s = Formatter.withSeparator.string(for: n)
// s is now "5,000"
But let's say what you start with really is a string. Then you could say, for example:
let str = "5000"
let s = Formatter.withSeparator.string(for: Float(str)!)
// s is now "5,000"
Observe that the decimal information is lost in this process. If that were important to you, you'd need to add that requirement to the formatter itself. You are making a string, and you have to provide all information about how you want that string to look. For example:
let str = "5000.00"
let f = Formatter.withSeparator
f.minimumFractionDigits = 2
let s = f.string(for: Float(str)!)
// s is now "5,000.00"
If you omit the mimimumFractionDigits
info, you would get "5,000"
again; the original appearance of the string we started with is completely unimportant.
Upvotes: 7