2016-12-17 4 views
0

ここにDecimalを取得するのに問題があります。 私はこのコードを試しましたが、結果は9.0です、どうすれば0.9を得ることができますか?文字列から10進数を取得する

let distances = "0.9 mil"  
let stratr = distances.characters.split{$0 == " "}.map(String.init) 
       for item in stratr { 
        let components = item.components(separatedBy: NSCharacterSet.decimalDigits.inverted) 
        let part = components.joined(separator: "") 

        if let doubVal = Double(part) { 
         print("this is a number -> \(doubVal)") 
        } 

答えて

0

文字列をスペース文字で区切り、最初のコンポーネントを使用してFloatを初期化できます。

let str = "0.9 mil" 
let decimal = str.components(separatedBy: " ").first.flatMap { Float($0) } 

print(decimal) // 0.9 
+1

これは非常に使いやすく、@ Callamよりも優れています – AlbertWu

1

String構造体は、所与のCharacterSetに基づいて文字を削除するために使用することができるインスタンスの方法を提供します。この場合、letterswhitespacesの文字セットを使用して小数点値を分離し、それからDecimalを作成することができます。

let distances = "0.9 mil" 

let decimal = Decimal(string: distances.trimmingCharacters(in: CharacterSet.letters.union(.whitespaces))) 

if let decimal = decimal { 
    print(decimal) // Prints 0.9 
} 
関連する問題