Jan 13, 2024
1 min read
In Java, rounding numbers to two decimal places is a common task. This can be achieved using the BigDecimal class, which provides precise arithmetic and rounding capabilities. Here’s a simple code snippet to demonstrate how to round a double to two decimal places:
|
|
Import BigDecimal: Begin by importing the BigDecimal class, which will be used for precise arithmetic.
Define roundToTwoDecimalPlaces method: This method takes a double value as input, converts it to a BigDecimal, and then rounds it to two decimal places using setScale with ROUND_HALF_UP rounding mode.
Example in main method: The main method demonstrates how to use the roundToTwoDecimalPlaces method with an example value. It prints the original and rounded values.
This code uses ROUND_HALF_UP rounding mode, which rounds towards “nearest neighbor” unless both neighbors are equidistant, in which case, it rounds up. Adjust the rounding mode as needed based on your requirements.
Sharing is caring!