Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Commons-math rounding double

I'm using commons-math 3.6.1.

I need to round a double value to 2 decimal

Let's assume this is my double value:

double d = 400.54540997260267;

Now by rounding this number I was expecting as result 400.54

Instead if my number was double d1 = 400.54640997260267; I was expecting as result 400.55

Now I'm using this code:

Precision.round(d, 2, BigDecimal.ROUND_DOWN);

If I use as roundingMethod BigDecimal.ROUND_DOWN I always get the lowest rounding. Which kind of rounding method should I use in order to get what I was expecting?

I tried the following code:

public class TestCalcoli

    {
        private static final Logger logger = LoggerFactory.getLogger(TestCalcoli.class.getName());
        private void calc(double d)
        {
            double result = Precision.round(d, 2, BigDecimal.ROUND_HALF_DOWN);
            double result2 = Precision.round(d, 2, BigDecimal.ROUND_HALF_UP);
            logger.info("d--> "+d+" result --> "+result+" result2 --> "+result2);
        }
        @Test
        public void calcola()
        {
            try
            {
                double d = 400.54540997260267;
                double d1 = 400.54640997260267;
                calc(d1);
                calc(d);
            }
            catch (Exception e)
            {
                logger.error("errore", e);
            }
        }
    }

CONSOLE OUTPUT:

2017-07-31 09:29:44,608 317  [main] INFO  i.e.c.r.pwb.test.TestCalcoli - d--> 400.54640997260265 result --> 400.55 result2 --> 400.55
2017-07-31 09:29:44,612 321  [main] INFO  i.e.c.r.pwb.test.TestCalcoli - d--> 400.54540997260267 result --> 400.55 result2 --> 400.55
like image 279
Angelo Immediata Avatar asked Jul 31 '17 07:07

Angelo Immediata


1 Answers

You should use HALF_UP if you want to round up for same distance, i.e. digit 5.

like image 76
milbrandt Avatar answered Oct 04 '22 13:10

milbrandt