How do I round a number in Groovy? I would like to keep 2 decimal places.
For example (pseudo-code):
round(1.2334695) = 1.23 round(1.2686589) = 1.27
Put simply, if the last digit is less than 5, round the previous digit down. However, if it's 5 or more than you should round the previous digit up. So, if the number you are about to round is followed by 5, 6, 7, 8, 9 round the number up. And if it is followed by 0, 1, 2, 3, 4 round the number down.
The ROUND function rounds a number to a specified number of digits. For example, if cell A1 contains 23.7825, and you want to round that value to two decimal places, you can use the following formula: =ROUND(A1, 2) The result of this function is 23.78.
math. BigDecimal is the default type for non-integer floating types. Because of default imports we don't have to import the BigDecimal class, but we can use it right away. To create a BigDecimal (or BigInteger ) we can use the "G" or "g" suffix.
If you're dealing with doubles or floats
You can simply use
assert xyz == 1.789 xyz.round(1) == 1.8 xyz.round(2) == 1.79
You can use:
Math.round(x * 100) / 100
If x
is a BigDecimal
(the default in Groovy), this will be exact.
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