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:
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 up to two decimal places:
double num = 3.14159;
DecimalFormat df = new DecimalFormat("#.##");
double rounded = Double.parseDouble(df.format(num));
This will also round the number 3.14159
up to 3.15
.
Note that the Math.ceil
method and the DecimalFormat
class will both round the number up to the nearest two decimal places, rather than simply truncating the decimal part of the number.