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
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.
Int rounds down to the nearest integer. Trunc truncates the number to just the integer portion by removing any decimal portion.
The answer is Yes. Java does a round down in case of division of two integer numbers.
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
let value = 1397968
let rounded = Int(round(Double(value) / 100) * 100)
print(rounded)
-> 1398000
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