这里有一个问题,如果我使用解析字符串作为计算器程序的结果,
4.5 * 5.0 = 22.5
如何在这里使用拆分从结果中删除小数部分?
答案 0 :(得分:1)
从结果中使用modf
extract
decimal
part
。
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);
只需要来自浮动的双倍内容
只需要integer
的{{1}}值,然后
double
只需要 let integerValue:Int = Int(integral)
println(integerValue)
的{{1}}值,然后
integer
答案 1 :(得分:1)
假设您只使用字符串:
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
}