在Swift中将String类型的字符串转换成floate或double的若干方法:
1._bridgeToObjectiveC()
let version: String = UIDevice.currentDevice().systemVersion
let versionFloat = version._bridgeToObjectiveC().floatValue
if versionFloat < 8.0 {
cell.textLabel?.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
}
2.as NSString
let version: String = UIDevice.currentDevice().systemVersion
let versionFloat = (version as NSString).floatValue // -> 8.1
3.CFStringGetDoubleValue()
let version: String = UIDevice.currentDevice().systemVersion
let versionFloat = CFStringGetDoubleValue(version)
println("\(versionFloat)") // -> 8.1
4.atof()/strtod()
strtod()会扫描参数nptr字符串,跳过前面的空格字符,直到遇上数字或正负符号才开始做转换,到出现非数字或字符串结束时(‘\0’)才结束转换,并将结果返回。若endptr不为NULL,则会将遇到不合条件而终止的nptr中的字符指针由endptr传回。参数nptr字符串可包含正负号、小数点或E(e)来表示指数部分。如123.456或123e-2。
let str = "0xff"
atof(str) // -> 255.0
strtod(str,nil) // -> 255.0
atof("123.4567fubar") // -> 123.4567
注:atof()和atof()可以接受进制数字,如上所示
5.NSNumberFormatter
var formatter = NSNumberFormatter()
let valueStr = "1234.123"
let oldNumber = formatter.numberFromString(valueStr)
formatter.groupingSeparator = " "
formatter.decimalSeparator = "|"
formatter.numberStyle = .DecimalStyle
formatter.formatterBehavior = .BehaviorDefault
let numberStr = formatter.stringFromNumber(oldNumber!)
println("\(numberStr!)") //1 234|123