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!
Asked
Active
Viewed 167 times
0

rmaddy
- 314,917
- 42
- 532
- 579

orthehelper
- 4,009
- 10
- 40
- 67
-
2just a note, that is not casting but converting. Have you tried *converting* the string to a double and go from there? – luk2302 Jul 17 '17 at 15:25
-
Thats my solution now but i was looking for more elegant way – orthehelper Jul 17 '17 at 15:28
-
Try Here : https://stackoverflow.com/a/39658447/6479530 – Rajamohan S Jul 17 '17 at 15:42
3 Answers
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
-
Yeah, I wouldn't go with the latter because it is impossible to distinguish a string `"0"` from an invalid number. – JeremyP Jul 17 '17 at 15:56
-
I would also add `let someInt = Int(round(aDouble))` as option – Vasilii Muravev Jul 17 '17 at 16:48
-
@VasiliiMuravev Whether the `Double` should be rounded or not is a separate decision and not really important to the question. – rmaddy Jul 17 '17 at 16:49
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
-
-
@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