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 !

1
  • 3
    print(Int(Float(floatstring)!)) Commented Aug 24, 2016 at 9:09

5 Answers 5

18

Option 1

let intNum = Int(Float(floatstring)!)

Option 2

if floatstring.rangeOfString(".") != nil {
    let i = Int(floatstring.componentsSeparatedByString(".").first!)
    print(i)
}
Sign up to request clarification or add additional context in comments.

Comments

4

It should work like this:

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

let floatstring : String = "23.24" 
print(Int(Float(floatstring)!))

Comments

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

Comments

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;

Comments

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!)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.