I use ordinary math 3.6.1.
I need to round double value to 2 decimal
Suppose this is my double value:
double d = 400.54540997260267;
Now, rounding this number, I was expecting 400.54 as the result
Instead, if my number were double, d1 = 400.54640997260267; I was expecting a result of 400.55
I am using this code now:
Precision.round(d, 2, BigDecimal.ROUND_DOWN);
If I use BigDecimal.ROUND_DOWN rounding as BigDecimal.ROUND_DOWN I always get the lowest rounding value. What rounding method should I use to get what I expected?
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 EXIT:
2017-07-31 09:29:44,608 317 [main] INFO iecrpwb.test.TestCalcoli - d--> 400.54640997260265 result --> 400.55 result2 --> 400.55 2017-07-31 09:29:44,612 321 [main] INFO iecrpwb.test.TestCalcoli - d--> 400.54540997260267 result --> 400.55 result2 --> 400.55