PSR
PSR

Reputation: 40318

Why here different results in java for long and double with same values

public static void main(String[] args) {
        double firstDouble = 1.8d;
        double secondDouble = 1.65d;


        float firstFloat = 1.8f;
        float secondFloat = 1.65f;
        System.out.println("DOUBLE SUM : "+(firstDouble + secondDouble));
        System.out.println("FLOAT SUM :"+(firstFloat + secondFloat));

        System.out.println("DOUBLE SUM"+firstDouble + secondDouble);
        System.out.println("FLOAT SUM"+firstFloat + secondFloat);
    }

OUT PUT:

DOUBLE SUM : 3.45
FLOAT SUM :3.4499998

DOUBLE SUM :1.81.65
FLOAT SUM :1.81.65

my questions

1) In the first set of out put why it is giving different values 3.45 and 3.4499998 for the same values 2) In the second set of out put why the out put is different from first out put.

Thanks in advance...

Upvotes: 2

Views: 470

Answers (4)

Howard Lin
Howard Lin

Reputation: 41

This is very useful: http://floating-point-gui.de/languages/java/

For a short answer, try to use BigDecimal whenever you are dealing with floating points.

BigDecimal a = new BigDecimal("1.8");
BigDecimal b = new BigDecimal("1.65");
BigDecimal c = a.add(b); // returns a BigDecimal representing exactly 3.45

Upvotes: 0

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41200

System.out.println("DOUBLE SUM"+firstDouble + secondDouble);

Here argument takes as a String. and plus/addition operator works as String concatition. Bracket has more priortity so that evalutes first.

First question is already answered. Please find here

Upvotes: 1

BlacKow
BlacKow

Reputation: 316

1) because float isn't precise enough to calculate sum with precision better than (3.45-3.4499998)=2E-7 http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.2.3

2) "DOUBLE SUM"+firstDouble converts firstDouble into a String and concatenates them, then it concatenate secondDouble. When you put ( ) it calculates the sum first and the concatenates result to "DOUBLE SUM"

Upvotes: 0

Sridhar
Sridhar

Reputation: 1962

In the second set you missed the brackets , it is doing something else with the String in the System.out.println statement "Double sum " and "Float sum ", so add brackets with your arithmetic expressions to get the correct result.

System.out.println("DOUBLE SUM : "+(firstDouble + secondDouble));
System.out.println("FLOAT SUM :"+(firstFloat + secondFloat));

System.out.println("DOUBLE SUM"+ (firstDouble + secondDouble));
System.out.println("FLOAT SUM"+(firstFloat + secondFloat));

This gives

DOUBLE SUM 3.45
FLOAT SUM 3.4499998
DOUBLE SUM 3.45
FLOAT SUM 3.4499998

Upvotes: 0

Related Questions