December 7, 2023

Java – How to round double / float value to 2 decimal places

There are a few ways to round float or double to 2 decimal places in Java. In short, for monetary calculation, picks BigDecimal; for display purpose, picks DecimalFormat(“0.00”). We can use DecimalFormat(“0.00”) to ensure the number always round to 2 decimal places. For DecimalFormat, the default rounding mode is RoundingMode.HALF_EVEN, and we can use setRoundingMode(RoundingMode) to set a specified rounding mode. We also can convert the double to a BigDecimal object and set the scale and rounding mode. The String.format is working fine, and the default rounding is half-up; however, we have no way to configure the type of rounding mode.

Java – How to round double / float value to 2 decimal places Read More

Java – Display double in 2 decimal places

In Java, there are few ways to display double in 2 decimal places. We can use DecimalFormat(“0.00”) to ensure the number is round to 2 decimal places. We also can use String formater %2f to round the double to 2 decimal places. However, we can’t configure the rounding mode in String.format, always rounding half-up. We can convert double value to BigDecimal to set scale to 2 decimal places.

Java – Display double in 2 decimal places Read More

How to calculate monetary values in Java

There are many monetary values calculation in the financial or e-commerce application, and there is one question that arises for this – Should we use double or float data type to represent the monetary values? Answer: Always uses java.math.BigDecimal to represent the monetary values. With double or float – It cannot calculate all the decimals precisely. To avoid the decimal issue above, we can use BigDecimal to represent the monetary values; furthermore, we can control the BigDecimal scale much more straightforward. BigDecimal performs exact decimal arithmetic.

How to calculate monetary values in Java Read More