number of decimal places in a double

H

harryos

hi
I am trying this calculation

double a=2.2;
double b=1.8;
double sum=a+b;
double diff=a-b;
double remainder=a%b;

when I print the values of these, I get
a=2.2
b=1.8
sum=4.0
diff=0.40000000000000013
remainder=0.3999999999999988

In my calculations, I want to use diff as 0.4 instead of
40000000000000013 .Also I would like to get remainder as 0.4 instead
of 0.3999999999999988.
Is there some way to do this using any java api?
thanks
harry.
 
M

markspace

harryos said:
hi
I am trying this calculation

double a=2.2;
double b=1.8;
double sum=a+b;
double diff=a-b;
double remainder=a%b;

when I print the values of these, I get

1) print with printf, and specify a precision

System.out.printf( "%.6f", diff );

I think will do it.

2) Use BigDecimal.
 
J

Joshua Cranmer

hi
I am trying this calculation

double a=2.2;
double b=1.8;
double sum=a+b;
double diff=a-b;
double remainder=a%b;

when I print the values of these, I get
a=2.2
b=1.8
sum=4.0
diff=0.40000000000000013
remainder=0.3999999999999988

In my calculations, I want to use diff as 0.4 instead of
40000000000000013 .Also I would like to get remainder as 0.4 instead
of 0.3999999999999988.
Is there some way to do this using any java api?

There is no way to get 0.4 as a floating-point number since the number
2/5 has an infinite expansion in binary. There is a number closest to
that value in the floating point representation, and the Java
double-to-String conversion routines magically detect that and print out
the simple numbers (see
<http://java.sun.com/javase/6/docs/api/java/lang/Double.html#toString(double)>).

For most floating point comparisons, you need to consider answers to
within an epsilon (10^-6 is generally good enough for many applications;
see the field of numerical analysis for much more information). For
printing out, you can generally limit the number of significant figures
to a few (6 is again generally good enough).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top