这里的问题是,如果我使用解析字符串来处理计算器程序的结果,
我该如何在这里使用分割函数来将结果中的小数部分分离出来?
4.5 * 5.0 = 22.5
我该如何在这里使用分割函数来将结果中的小数部分分离出来?
使用 modf
函数从结果中提取小数部分。
Objective-C:
double integral = 22.5;
double fractional = modf(integral, &integral);
NSLog(@"%f",fractional);
Swift :
var integral:Double = 22.5;
let fractional:Double = modf(integral,&integral);
println(fractional);
从浮点数中获取整数部分
如果只想要从 double
中获取其 integer
值,则可以:
let integerValue:Int = Int(integral)
println(integerValue)
let integerValue:Float = Float(integral)
println(integerValue)
var str = "4.5 * 5.0 = 22.5 "
// Trim your string in order to remove whitespaces at start and end if there is any.
var trimmedStr = str.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
// Split the string by " " (whitespace)
var splitStr = trimmedStr.componentsSeparatedByString(" ")
// If the split was successful, retrieve the last past (your number result)
var lastPart = ""
if let result = splitStr.last {
lastPart = result
}
// Since it's a XX.X number, split it again by "." (point)
var splitLastPart = lastPart.componentsSeparatedByString(".")
// If the split was successful, retrieve the last past (your number decimal part)
var decimal = ""
if let result = splitLastPart.last {
decimal = result
}
count
测试接着使用 last!
,你应该使用 if let
语法:if let result = splitStr.last { lastPart = result }
。 !
是危险的,只有在没有实际替代方案时才应该使用。 - Airspeed VelocitySwift.split
,它类似于componentsSeparatedByString
。以下是翻译的代码:if let result = last(split(str) { $0 == " " }), let decimal = last(split(result) {$0 == "."}) { println(decimal) }
- Airspeed Velocity