Harry Perez
Harry Perez

Reputation: 31

How do I get what I want with Math.round in JAVA?

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

Answers (3)

Elliott Frisch
Elliott Frisch

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

wassgren
wassgren

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

Lrrr
Lrrr

Reputation: 4817

if your output is a double it will work fine look here

public static void main (String[] args) throws java.lang.Exception
{
    double a = Math.round(83.5067 * 100) / 100.0;
    System.out.println(a);
}

will print 83.51

Upvotes: 1

Related Questions