How do I convert a string containing both numbers and characters?
The string looks like this
"135,00 kr"
And I want to make it
135,00
Thanks!
How do I convert a string containing both numbers and characters?
The string looks like this
"135,00 kr"
And I want to make it
135,00
Thanks!
You could take a "brute force" approach and remove all non-numerics characters from the string and use the internal type conversions directly.
let numberString = "135,05 kr"
let decimalSeparator = Locale.current.decimalSeparator ?? "."
let decimalFilter = CharacterSet(charactersIn:"-0123456789" + decimalSeparator)
let number = Float(numberString.components(separatedBy:decimalFilter.inverted)
.joined(separator:""))
This will clean up any non numeric characters from the string. So it will not be affected by inconsistent thousand separators or variations of the currency symbol (e.g. if you're working with multiple currencies). You do have to be consistent on the decimal separators though.
func number() -> Double? {
let str = String(self.characters.filter { "01234567890.".characters.contains($0) })
return Double(str)
}
add this as an extension to String
Try this:
let label = "135,00 kr"
let space = label.characters.index(of: " ")
let number = String(label.characters.prefix(upTo: space!))
let formatter = NumberFormatter()
formatter.decimalSeparator = ","
let formatted = formatter.number(from: number)
let double = formatted?.doubleValue