Ios 在Swift中将字符串(浮点值)转换为int

Ios 在Swift中将字符串(浮点值)转换为int,ios,swift,string,Ios,Swift,String,你好,我有字符串“(带floatvalue)” 我想将floatString转换为Int。 谢谢大家! 选项1 let intNum = Int(Float(floatstring)!) 选项2 if floatstring.rangeOfString(".") != nil { let i = Int(floatstring.componentsSeparatedByString(".").first!) print(i) } 它应该是这样工作的: 您可以将字符串转换为浮

你好,我有字符串“(带
float
value)”

我想将float
String
转换为
Int

谢谢大家!

选项1

let intNum = Int(Float(floatstring)!)
选项2

if floatstring.rangeOfString(".") != nil {
    let i = Int(floatstring.componentsSeparatedByString(".").first!)
    print(i)
}

它应该是这样工作的:


您可以将字符串转换为浮点数,然后再转换为整数

if let floatValue = Float(floatString) {
    if let intValue = Int(floatValue) {
        print(intValue) //that is your Int
    }
}
如果它不打印任何内容,则该字符串不是“floatString”。 顺便说一句,你可以简单地通过组合这些问题的答案来找到答案

试试这个

let floatValue = "23.24".floatValue  // first convert string to float
let intValue:Int? = Int(floatValue)  // then convert float to int 
print(intValue!)
1.对于Swift 2.0

let intValue=int(float(floatString))
2.对于较旧版本的Swift

let floatValue = (floatString.text as NSString).floatValue
let intValue:Int? = Int(floatValue) 
3.目标C

floatValue = [floatString floatValue];
int intValue:Int = (int) floatValue;
print(Int(Float(floatstring)!)
let floatValue = (floatString.text as NSString).floatValue
let intValue:Int? = Int(floatValue) 
floatValue = [floatString floatValue];
int intValue:Int = (int) floatValue;