5

Hello I have string "(with float value)"

let floatstring : String = "23.24" 
print(floatstring)

I want to convert float String to Int. Thank you !

Nirav D
  • 71,513
  • 12
  • 161
  • 183
SwiftDeveloper
  • 7,244
  • 14
  • 56
  • 85

5 Answers5

18

Option 1

let intNum = Int(Float(floatstring)!)

Option 2

if floatstring.rangeOfString(".") != nil {
    let i = Int(floatstring.componentsSeparatedByString(".").first!)
    print(i)
}
Nirav D
  • 71,513
  • 12
  • 161
  • 183
4

It should work like this:

http://swiftlang.ng.bluemix.net/#/repl/57bd6566b36620d114f80313

let floatstring : String = "23.24" 
print(Int(Float(floatstring)!))
Edder Núñez
  • 165
  • 2
  • 8
2

You can cast the String to a Float and then to an Int.

if let floatValue = Float(floatString) {
    if let intValue = Int(floatValue) {
        print(intValue) //that is your Int
    }
}

If it does not print anything then the string is not a 'floatString'. Btw you can simply find the answer by combining the answers to these Questions.

Stackoverflow: String to Int

Stackoverflow: Casting Float to Int

Community
  • 1
  • 1
Yannick
  • 3,210
  • 1
  • 21
  • 30
2

1.For Swift 2.0

let intValue=int(float(floatString))

2.For Older version of Swift

let floatValue = (floatString.text as NSString).floatValue
let intValue:Int? = Int(floatValue) 

3.For objective-C

floatValue = [floatString floatValue];
int intValue:Int = (int) floatValue;
Deepraj Chowrasia
  • 1,349
  • 10
  • 20
1

Try This

let floatValue = "23.24".floatValue  // first convert string to float
let intValue:Int? = Int(floatValue)  // then convert float to int 
print(intValue!)
Sudhir
  • 127
  • 1
  • 12