Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use parse string in swift?

An issue here to me that if i use parse string for the result of calculator program for instance,

4.5 * 5.0 = 22.5 

how can I use splitting here to depart decimal part from result?

like image 520
legolas Avatar asked May 03 '26 18:05

legolas


1 Answers

Assuming you're working with strings only :

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
}
like image 177
lchamp Avatar answered May 05 '26 08:05

lchamp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!