0

Im working with a service that send back values of type String which contains floating point like Double as so for example "1240.86". I want to cast it to Int and when i try to convert like so Int(stringObject) the cast fails when the values have floating points. How can i cast it? Thanks!

rmaddy
  • 314,917
  • 42
  • 532
  • 579
orthehelper
  • 4,009
  • 10
  • 40
  • 67

3 Answers3

3

Try it in two steps:

if let aDouble = Double(someString) {
    let someInt = Int(aDouble)
}

or possibly:

let someInt = Int(Double(someString) ?? 0)

though the latter is a bit of a kludge since you probably don't want to force a value of 0 if the string isn't a valid number.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
2

You could use the map(_:) method of Optional to optionally chain a conversion (initialization by, specifically) from String to Double followed by one from Double to Int and conditionally bind the resulting integer in case it is not nil (i.e. successfully converted):

let str = "1240.86"
if let number = Double(str).map(Int.init) {
    // number is of type Int and, in this example, of value 1240
}
dfrib
  • 70,367
  • 12
  • 127
  • 192
  • @down voter: consider giving feedback rather than a drive-by down vote. Or is this just an anger down vote ...? – dfrib Jul 17 '17 at 16:46
  • I didn't know about the `Optional map` function. I like this. – rmaddy Jul 17 '17 at 16:53
  • @rmaddy most of the time its use cases can be replaced simply by optional chaining, but for cases such as this one it can be a good approach. Also note that there's a `flatMap(_:)` method of `Optional` which can also sometimes be of use (passes the single argument as an optional without unwrapping it). – dfrib Jul 17 '17 at 17:00
0

You can separate string by dot .:

func printInt(from str: String) {
    let intValue = Int(str.components(separatedBy: ".")[0]) ?? 0
    print(intValue)
}

printInt(from: "1234.56")   // 1234
printInt(from: "1234")      // 1234
printInt(from: "0.54")      // 0
printInt(from: ".54")       // 0
printInt(from: "abc")       // 0
Vasilii Muravev
  • 3,063
  • 17
  • 45