Skip to content

round up to 2 decimal places in java?

To round a number up to two decimal places in Java, you can use the Math.ceil method and multiply the number by 100, then divide the result by 100.

Here's an example of how you can do this:


java
double num = 3.14159;
double rounded = Math.ceil(num * 100) / 100;

This will round the number 3.14159 up to 3.15.

Alternatively, you can use the DecimalFormat class to round the number to two decimal places:


java
import java.text.DecimalFormat;

double num = 3.14159;
DecimalFormat df = new DecimalFormat("#.##");
double rounded = Double.parseDouble(df.format(num));

This will round the number 3.14159 to 3.14.

Note that Math.ceil always rounds toward positive infinity, so it will round negative numbers up (e.g., -3.14159 becomes -3.14). DecimalFormat uses standard rounding (half-up) by default, not strictly rounding up. For precise decimal rounding, BigDecimal is the recommended approach:


java
import java.math.BigDecimal;
import java.math.RoundingMode;

double num = 3.14159;
BigDecimal bd = new BigDecimal(Double.toString(num));
double rounded = bd.setScale(2, RoundingMode.CEILING).doubleValue();

This will round 3.14159 up to 3.15.

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.