Rounding issue in double calculation

    double pine = 2.5;
    double alp = 2.54 - pine;
    System.out.println( "alp is " + alp);
    if (alp == 0.04){
        System.out.println ("true");
    }else{
        System.out.println ("false");
    }

I'm relatively new to programming (and this site) and I just ran into this problem trying to calculate double values... In the code above, so far from a day of searches, I understand that alp is 0.0400000000000...36 because double values have to store their numbers in terms of powers of 2...

BUT, I want to make it so that the if statement above prints "true" (i.e. treat alp as 0.04). How can I make this happen?

Upvotes: 0

Views: 74

Answers (4)

dan_s
dan_s

Reputation: 471

You could compare them like this (where precision depends on the application):

double pine = 2.5;
double alp = 2.54 - pine;
double precision = 0.0000001;
System.out.println( "alp is " + alp);

if (Math.abs(alp - 0.04) <= precision) {
    System.out.println ("true");
}else{
    System.out.println ("false");
}

Or you could use Java's BigDecimal class:

BigDecimal pine = new BigDecimal("2.5");
BigDecimal alp = new BigDecimal("2.54");
alp = alp.subtract(pine);
if (alp.compareTo(new BigDecimal("0.04"))) {
    System.out.println ("true");
}else{
    System.out.println ("false");
}

It is recommended to use the String constructor to avoid errors.

Upvotes: 3

Paolo de Roxas
Paolo de Roxas

Reputation: 129

You can use DecimalFormat and set the expected format. Or as others have suggested, use the BigDecimal class.

DecimalFormat newFormat = new DecimalFormat("#.##");
double pine = 2.5;
double alp = Double.valueOf(newFormat.format(2.54 - pine));
System.out.println( "alp is " + alp);

if (alp == 0.04){
    System.out.println ("true");
}else{
    System.out.println ("false");
}

Upvotes: 1

Quicksilver002
Quicksilver002

Reputation: 735

Do

...
if(Math.abs(alp - 0.04) < 0.0000000001){//some really small number
  System.out.println("true");
}
...

Upvotes: 1

Alexandru Godri
Alexandru Godri

Reputation: 538

Try this:

double pine = 2.5;
double alp = 2.54 - pine;
alp = Math.round(alp * 100.0) / 100.0;
System.out.println( "alp is " + alp);
if (alp == 0.04) {
    System.out.println ("true");
} else {
    System.out.println ("false");
}

Upvotes: 1

Related Questions