Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I round a number in Groovy?

Tags:

groovy

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 
like image 975
Georgian Citizen Avatar asked Dec 30 '10 06:12

Georgian Citizen


People also ask

How do you round a number?

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.

What is round () function?

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.

How do I use BigDecimal in Groovy?

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.


2 Answers

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 
like image 118
john Smith Avatar answered Sep 19 '22 05:09

john Smith


You can use:

Math.round(x * 100) / 100 

If x is a BigDecimal (the default in Groovy), this will be exact.

like image 39
Matthew Flaschen Avatar answered Sep 17 '22 05:09

Matthew Flaschen