AlbertWu
AlbertWu

Reputation: 59

Get a Decimal from a String

I have a problem to get a Decimal here. I have tried this code but the results is 9.0 , How can i get 0.9 ?

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)")
    }
}

Upvotes: 2

Views: 2534

Answers (4)

Islam
Islam

Reputation: 3734

extension String {
    /// "0.9 mil" => "0.9"
    var decimals: String {
        return trimmingCharacters(in: CharacterSet.decimalDigits.inverted)
    }

    /// "0.9" => 0.9
    var doubleValue: Double {
        return Double(self) ?? 0
    }
}

Usage:

let distance = "0.9 mil"
print(distance.decimals) // "0.9"
print(distance.decimals.doubleValue) // 0.9
print(distance.doubleValue) // 0 (because Double("0.9 mil") => nil)

Upvotes: 1

Ryan H.
Ryan H.

Reputation: 2593

The String struct provides an instance method that can be used to remove characters based on a given CharacterSet. In this case, you can use the letters and whitespaces character sets to isolate your decimal value and then create a Decimal from it.

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
}

Upvotes: 1

AlbertWu
AlbertWu

Reputation: 59

Never mind i find the Answer

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)")
                }

I think when i set Joined(separator : ".") it will joined the String with an "." as separator

Upvotes: 0

Callam
Callam

Reputation: 11539

You can separate the string by the space character and then initialize a Float using the first component.

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

print(decimal) // 0.9

Upvotes: 1

Related Questions