3

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?

1
  • i mean if the result is 22.0 , i want just 22 not 22.0, of course if it is 22.5 , 0.5 will be there as a 22.5, but 0 of 22.0 for the result which is 22.0 or when typeing numbers 22.0 instead of 22 should not be on right side of point ? Commented Mar 3, 2015 at 0:52

2 Answers 2

1

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

Instead of using a test of count followed by last!, you should use if let syntax: if let result = splitStr.last { lastPart = result }. ! is dangerous and should only be used when there’s no practical alternative.
NP. Also, check out Swift.split which is similar to componentsSeparatedByString: if let result = last(split(str) { $0 == " " }), let decimal = last(split(result) {$0 == "."}) { println(decimal) }
1

Use modf to extract decimal part from result.

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);

Want only interger part from double of float

Want only integer value from double then

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

Want only integer value from float then

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

1 Comment

i mean if the result is 22.0 , i want just 22 not 22.0, of course if it is 22.5 , 0.5 will be there as a 22.5, but 0 of 22.0 for the result which is 22.0 or when typeing numbers 22.0 instead of 22 should not be on right side of point ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.