Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I format double input in Java WITHOUT rounding it?

I have read this question Round a double to 2 decimal places It shows how to round number. What I want is just simple formatting, printing only two decimal places. What I have and what I tried:

double res = 24.695999999999998;
DecimalFormat df = new DecimalFormat("####0.00");
System.out.println("Value: " + df.format(res)); //prints 24.70 and I want 24.69
System.out.println("Total: " + String.format( "%.2f", res )); //prints 24.70

So when I have 24.695999999999998 I want to format it as 24.69

like image 881
sammy333 Avatar asked Dec 05 '22 22:12

sammy333


1 Answers

You need to take the floor of the double value first - then format it.

Math.floor(double)

Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer.

So use something like:

double v = Math.floor(res * 100) / 100.0;

Other alternatives include using BigDecimal.

public void test() {
    double d = 0.29;
    System.out.println("d=" + d);
    System.out.println("floor(d*100)/100=" + Math.floor(d * 100) / 100);
    System.out.println("BigDecimal d=" + BigDecimal.valueOf(d).movePointRight(2).round(MathContext.UNLIMITED).movePointLeft(2));
}

prints

d=0.29
floor(d*100)/100=0.28
BigDecimal d=0.29
like image 68
OldCurmudgeon Avatar answered Dec 23 '22 11:12

OldCurmudgeon