简体   繁体   中英

Shifting Math.ceil in Java

I want to perform a ceiling function on a number (33.1504352455) so that it returns 33.16. When using ceiling, of course, it returns 34.0. How would I shift the character that the ceiling is acting on so that it returns 33.16?

You could try

number = Math.ceil(oldnumber * 100) / 100.0;

But this could be subject to the vagaries of floating point math.

For better precision, always opt for BigDecimal. You could do it like:

BigDecimal b = new BigDecimal(33.1504352455);
b = b.setScale(2, RoundingMode.CEILING)
System.out.println(b);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM