Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round Integer Numbers in Swift

Tags:

swift

I would like to round the integer number to the nearest hundredth for currency purposes, How is it possible in Swift?

Example: 1397968 becomes 1397900

like image 247
rony Avatar asked Dec 03 '16 18:12

rony


People also ask

How do you round integer numbers?

Rounding to the Nearest Integer If the digit in the tenths place is less than 5, then round down, which means the units digit remains the same; if the digit in the tenths place is 5 or greater, then round up, which means you should increase the unit digit by one.

Do ints round down or up?

Int rounds down to the nearest integer. Trunc truncates the number to just the integer portion by removing any decimal portion.

Do integers round in Java?

The answer is Yes. Java does a round down in case of division of two integer numbers.


2 Answers

If you want to round down to a multiple of 100 then you can do that with (as @vadian said in a comment):

let amount = 1397968
let rounded = amount/100 * 100
print(rounded) // 1397900

This works because integer division truncates the result towards zero: amount/100 evaluates to 13979, and multiplying by 100 again gives 1397900.

But you asked for the nearest multiple of 100 for a given integer, and that can be done with a small modification:

let amount = 1397968
let rounded = (amount + 50)/100 * 100
print(rounded) // 1398000

for nonnegative integers. If you have both positive and negative values then @shallowThought's answer is probably the easiest way to go. But it can be done with pure integer arithmetic as well (using the approach from Make Int round off to nearest value):

func roundToHundreds(_ value: Int) -> Int {
    return value/100 * 100 + (value % 100)/50 * 100
}

roundToHundreds(123) // 100
roundToHundreds(188) // 200

roundToHundreds(-123) // -100
roundToHundreds(-188) // -200

This works for the full range of Int:

roundToHundreds(Int.max) // 9223372036854775800
roundToHundreds(Int.min) // -9223372036854775800
like image 171
Martin R Avatar answered Nov 18 '22 21:11

Martin R


let value = 1397968
let rounded = Int(round(Double(value) / 100) * 100)
print(rounded)

-> 1398000

like image 40
shallowThought Avatar answered Nov 18 '22 22:11

shallowThought