Home > Net >  Rounding down a float number to 2 decimal points in java
Rounding down a float number to 2 decimal points in java

Time:10-01

I have a variable x that is 11.885, when I round this to 2 decimal points I want it to give me 11.88 but it won't work and I can't figure it out. I won't be using import or anything but just can't figure out a way to round this number down.

What I originally used:

double x = 11.885     
double y = (double) Math.round(x * 100.0) / 100.0;

but this gives me 11.89. I also need this without printing it since I will be using this rounded number in my code.

CodePudding user response:

Try BigDecimal It has a lot of helpful features like this.

double x = 11.885;
BigDecimal y = BigDecimal.valueOf(x);
y.setScale(2, BigDecimal.ROUND_HALF_UP)

CodePudding user response:

Instead of Math.round(double), use Math.floor(double) like

double x = 11.885;
double y = Math.floor(x * 100) / 100.0;
System.out.println(y);

I get (as requested)

11.88
  • Related