I'd like to round my values to the closest of 5 cent for example:
5.31 -> 5.30
5.35 -> 5.35
5.33 -> 5.35
5.38 -> 5.40
Currently I'm doing it by getting the decimal values using:
let numbers = 5.33
let decimal = (numbers - rint(numbers)) * 100
let rounded = rint(numbers) + (5 * round(decimal / 5)) / 100
// This results in 5.35
I was wondering if there's a better method with fewer steps because sometimes numbers - rint(numbers)
is giving me a weird result like:
let numbers = 12.12
let decimal = (numbers - rint(numbers)) * 100
// This results in 11.9999999999999
If you need to round a number to the nearest multiple of 5, you can use the MROUND function and supply 5 for number of digits. The value in B6 is 17 and the result is 15 since 15 is the nearest multiple of 5 to 17.
To round to the nearest 5, you can simply use the MROUND Function with multiple = 5. By changing 5 to 50, you can round to the nearest 50 or you can use . 5 to round to the nearest .
When rounding to the nearest dollar, round the monetary amount up when the number to the right, immediately following the decimal point, is five or more. Keep the monetary amount the same if the number after the decimal point is four or less. In the example: $175.439 rounds down to $175 because 4 is less than 5.
Rounding means replacing a number with an approximate value that has a shorter, simpler, or more explicit representation. For example, replacing $23.4476 with $23.45, the fraction 312/937 with 1/3, or the expression √2 with 1.414.
Turns out..it's really simple
let x: Float = 1.03 //or whatever value, you can also use the Double type
let y = round(x * 20) / 20
It's really better to stay away from floating-point for this kind of thing, but you can probably improve the accuracy a little with this:
import Foundation
func roundToFive(n: Double) -> Double {
let f = floor(n)
return f + round((n-f) * 20) / 20
}
roundToFive(12.12) // 12.1
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