2015-03-02 17 views
3

一個問題到我這裏來,如果我使用解析字符串比如計算器程序的結果,如何在swift中使用解析字符串?

4.5 * 5.0 = 22.5 

怎麼用分裂這裏出發小數部分的結果呢?

+0

我的意思是如果結果是22.0,我只想要22而不是22.0,當然如果是22.5,那麼0.5就會以22.5的形式出現,22.0的結果是22.0,或者是22.0 n鍵入數字22.0而不是22不應該在點的右側? – legolas 2015-03-03 00:52:41

回答

1

使用modfextractdecimalpart從結果。

Objective-C的

double integral = 22.5; 
double fractional = modf(integral, &integral); 
NSLog(@"%f",fractional); 

夫特

var integral:Double = 22.5; 
let fractional:Double = modf(integral,&integral); 
println(fractional); 

只想整數部分從雙浮子

想從double只有integer值,那麼

let integerValue:Int = Int(integral) 
println(integerValue) 

想從float只有integer值,那麼

let integerValue:Float = Float(integral) 
println(integerValue) 
+0

@legolas檢查swift代碼 – 2015-03-02 12:26:15

+0

我的意思是如果結果是22.0,我只想要22而不是22.0,當然如果它是22.5,那麼0.5將會以22.5的形式存在,但22.0的結果爲22.0或者當鍵入時數字22.0而不是22不應該在點的右側? – legolas 2015-03-03 02:32:55

+0

@legolas現在檢查 – 2015-03-03 11:01:36

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 
} 
+0

您應該使用'if let'語法:'if let result = splitStr.last {lastPart = result}',而不是使用'count'後跟'last!'的測試。 '!'是危險的,只有在沒有實際的選擇時才能使用。 – 2015-03-02 12:42:57

+1

NP。此外,檢查出'Swift.split'類似於'componentsSeparatedByString':'if let result = last(split(str){$ 0 ==「」}),讓decimal = last(split(result){$ 0 == == 「。」}){println(decimal)}' – 2015-03-02 12:48:27