Good evening:
I am having a problem rounding numbers with 3 or more decimals.
I have for example this number: 1544.565
And I am trying to round it to 1544.57
I have tried:
BigDecimal.ROUND_HALF_EVEN
BigDecimal.ROUND_UP
RoundingMode.HALF_EVEN
RoundingMode.HALF_UP
RoundingMode.CEILING
RoundingMode.UP
And all of them gave me the same wrong result: 1544.56 I am trying to obtain 1544.57
Any solutions please?
Try ROUND_UP
with scale 2:
BigDecimal bigDecimal = new BigDecimal("1544.565");
System.out.println(bigDecimal.setScale(2, BigDecimal.ROUND_UP)); // 1544.57
In JDK 1.8 you can use java.text.DecimalFormat
for this
new DecimalFormat("0.00").format(1544.565)
OUTPUT
1544.57
Read the doc to identify more pattern characters.
UPDATE 2 (answering this comment ):
You are using BigDecimal.ROUND_HALF_EVEN
use BigDecimal.ROUND_HALF_UP
instead.
Don't use BigDecimal.ROUND_UP
, it always rounds up the number.
BigDecimal.ROUND_HALF_UP
Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up.
~Java doc~
Example:
BigDecimal number = new BigDecimal("1544.565");
System.out.println(number.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
Output
1544.57
Confirmed here ;
double a = 1544.565;
double rounded = Math.round(a * 100.0) / 100.0;
System.out.println(rounded);
Outputs 1544.57
.
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.