I am trying to write a method that will check to see if the Double ends in .0 vs anything else. So for example checking if it is 2.0 vs 2.12345.
If it is 2.0 then I want it to display just 2, but if it is 2.12345 then show 2.12345.
I had the idea of writing a func that took the Double as a parameter and returned an Int, but if the input turns out to be .12345 it cannot return it.
So I was wondering if the way I was thinking would work with tweaking or if there is a much similar means.
I was thinking maybe the return type could somehow be both Int & Double, but I do not know how that would work.
This is what I have so far
private func checkIfWholeNumber(displayedDouble: Double) -> Int {
if displayedDouble.truncatingRemainder(dividingBy: 1) == 0 {
return Int(displayedDouble)
} else {
return //
}
}
Convert Double into Number and then to String if u want to show it on label
let i = 1.0
let j = 1.2345
// Value in String
let a = NSNumber(value: j).stringValue // "1.2345"
let b = NSNumber(value: i).stringValue // "1"
// Value in Double
let c = NSNumber(value: i).doubleValue // 1.0
let d = NSNumber(value: j).doubleValue // 1.2345
simply use rounded
function.
func check(val:Double)->Int?{
let rounded = val.rounded()
return rounded == val ? Int(rounded) : nil
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With