double operation precision issue

Prince

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?

Rehman

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);

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related