Reputation: 6384
I have to run some algorithms on certain health industry numbers for validations. One of them requires checking if a total at a certain point ends in zero, if not get the next highest number that ends in zero. I have this code but am wondering if there is a better way to do it:
let strTotal = String(iTotal)
var iSubtractor = iTotal
if Int(String(strTotal.last!))! != 0 {
var bIsZeroEnding = false
repeat {
iSubtractor += 1
let strSubstractor = String(iSubtractor)
if Int(String(strSubstractor.last!))! == 0 {
bIsZeroEnding = true
}
} while !bIsZeroEnding
}
Doh...I do see the typo in my var name...strSubstractor... :D
Upvotes: 0
Views: 322
Reputation: 13354
You can use ceil
. It works with both (non-negative) and (negative) numbers.
extension CGFloat {
func nearest(to num: CGFloat) -> CGFloat {
return num * ceil(self/num)
}
}
let value: CGFloat = 53.0
print(value.nearest(to: 10))
output: 60.0
Alternatively for pure int
you can get it with the help of remainder
operator (%)
.
let value: Int = 33
let rem: Int = value%10
// Here, If rem == 0 that means number is fully divisible by 10 (Contains 0 at last)
let result: Int = (rem == 0) ? value : value + (10 - rem)
Upvotes: 1
Reputation: 539925
I have this code but am wondering if there is a better way to do it
Yes, there is. Rounding up a (non-negative) integer to the next multiple of 10 can be far more simply done with
let roundedNumber = ((oldNumber + 9)/10) * 10
without the need for any conversion to strings. We add 9 and then round down to the next multiple of 10 (using the fact that integer division truncates the result to an integer result).
Upvotes: 4
Reputation: 5341
This is all you need to do:
var desiredNumber = ceil(Double(iTotal)/10)*10
How this method works:
Upvotes: 1