在Swift中如何使用解析字符串?

3
这里的问题是,如果我使用解析字符串来处理计算器程序的结果,
4.5 * 5.0 = 22.5 

我该如何在这里使用分割函数来将结果中的小数部分分离出来?

我是说如果结果是22.0,我只想要22而不是22.0,当然如果是22.5,0.5将作为22.5存在,但是对于结果为22.0的情况或者输入数字22.0而不是22的情况,小数点右侧不应该有0。 - legolas
2个回答

1

使用 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)

我的意思是如果结果是22.0,我只想要22而不是22.0。当然,如果是22.5,则会出现0.5作为22.5的一部分,但在结果为22.0或输入数字22.0时,小数点右侧不应出现0。 - legolas

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
}

与其使用 count 测试接着使用 last!,你应该使用 if let 语法:if let result = splitStr.last { lastPart = result }! 是危险的,只有在没有实际替代方案时才应该使用。 - Airspeed Velocity
1
请查看Swift.split,它类似于componentsSeparatedByString。以下是翻译的代码:if let result = last(split(str) { $0 == " " }), let decimal = last(split(result) {$0 == "."}) { println(decimal) } - Airspeed Velocity

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接