RockAndRoll
RockAndRoll

Reputation: 2277

double operation precision issue

I faced similar issue in javascript which i resolved by multiplying and divinding by 1000. How can I resolve this in Java?

Code snippet:

double a=Double.parseDouble("1.8")/100;
System.out.println(a);

Output:

0.018000000000000002

I want 0.018 as output. Suggestions?

Upvotes: 0

Views: 85

Answers (3)

Rahman
Rahman

Reputation: 3785

You can do :

 double a=Double.parseDouble("1.8")/100;
      DecimalFormat df=new DecimalFormat("0.000");
      String f = df.format(a); 
      try {
        double dblValue = (Double)df.parse(f) ;
        System.out.println(dblValue);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

or

      double dblValue2 = Math.round( a * 1000.0 ) / 1000.0;
      System.out.println(dblValue2);

Upvotes: 1

Sergej Werfel
Sergej Werfel

Reputation: 1365

Do you want to increase prevision, or to do pretty printing? If you want to print 0.018 you can use

System.out.printf("%.3f%n",a);

%.3f means print a floating number with 3 digits after '.'

%n means new line

You can look on this german site how to use printf. Just scroll down for listing 4.30 (you don't need to understand german to understand the example)

Upvotes: 1

javatutorial
javatutorial

Reputation: 1944

When you need great precision, it's better to stick to BigDecimal instead of using Double.

BigDecimal can hold arbitrary precision and size numbers, while Double has a limited precision due to its representation.

The downside is that BigDecimal has worse preformance, and that code writing is more verbose (BigDecimal cannot use '+', '-', etc. operators).

Upvotes: 1

Related Questions