[英]How do you use parse string in swift?
這里有一個問題,如果我使用解析字符串作為計算器程序的結果,例如,
4.5 * 5.0 = 22.5
如何在這里使用拆分從結果中刪除小數部分?
使用modf
從結果中extract
decimal
part
。
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)
假設您只使用字符串:
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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.