Reputation: 31
I'm using this code to round a value:
Math.round(x * 100) / 100.0;
But it doesn't return what I need.
E.g.: x = 83.5067
What I want: 83.51
What I get: 83.5
Upvotes: 1
Views: 226
Reputation: 201399
I suggest you use formatted output instead of rounding. Like,
double x = 83.5067;
System.out.printf("%.2f%n", x);
but, to do the requested rounding you might use
double x = 83.5067;
x = Math.round(x * 100);
x /= 100;
System.out.println(x);
Both output
83.51
Upvotes: 1
Reputation: 19201
I like to use BigDecimal
for these kind of operations.
// Round it
final BigDecimal myRoundedNumber = BigDecimal.valueOf(83.5067).setScale(2, RoundingMode.HALF_UP);
// If you need it as a double
final double d = myRoundedNumber.doubleValue();
The setScale
-method is flexible and you can set the number of decimals and the rounding mode you require.
Upvotes: 0