-1

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!

Victor
  • 1,603
  • 4
  • 17
  • 24

3 Answers3

2

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.

Alain T.
  • 40,517
  • 4
  • 31
  • 51
0
func number() -> Double? {
    let str = String(self.characters.filter { "01234567890.".characters.contains($0) })
    return Double(str)
}

add this as an extension to String

Q Liu
  • 737
  • 1
  • 5
  • 7
-4

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
pesch
  • 1,976
  • 2
  • 17
  • 29
  • 4
    Better to set up a NumberFormatter for currency formatting. That looks like Danish Kroner to me, and the decimal separator being a comma rather than a period makes me think it's a locale other than US. – Duncan C May 13 '17 at 20:39
  • 2
    Do not use the code in this answer. This is not the correct solution. – rmaddy May 13 '17 at 21:25
  • The code is not wong, there is no need to downvote. How would you solve for the string on the actual question? You can't use "kr" as .currencySymbol nor as .currencyCode – pesch May 14 '17 at 06:20