0

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

PruitIgoe
  • 6,166
  • 16
  • 70
  • 137
  • what exactly is iTotal? an int? – Akshansh Thakur Apr 12 '18 at 11:50
  • 1
    What about `let newNumber = ((oldNumber + 9)/10) * 10`, without all that string stuff ? – Martin R Apr 12 '18 at 11:51
  • what about `var value = 75` and then `repeat { value+=1 } while !(value%10) == 0))` – Vollan Apr 12 '18 at 11:53
  • i am a bit confused by the expression "next highest number": do you want the next, or the highest number of the remaining ones? let your list be 11, 20, 30. You've parsed 11; 20 is the next number, 30 is the highest. Is your list maybe sorted? I think it would be beneficial if you could edit your post including an example of your input list – Newton fan 01 Apr 12 '18 at 16:20

3 Answers3

4

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

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
1

This is all you need to do:

var desiredNumber = ceil(Double(iTotal)/10)*10

How this method works:

  • Let's assume our original number is 37. If we divide it by 10, we get 3.7.
  • If we ceil 3.7, we get 4. Multiplying it by the divider will get us 40. This works with every divider.
Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223
Akshansh Thakur
  • 5,163
  • 2
  • 21
  • 38
1

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)
TheTiger
  • 13,264
  • 3
  • 57
  • 82