# Issue with a double ... again

Sergey Gorovoy

Greenhorn

Posts: 3

posted 15 years ago

I know that there are issues arising from using primitives of data type double in mathematical expressions. Somewhere in the earlier polsts it was suggested to use Math.round(a), where a is a double. However, when I execute the following:

...

double x = 27.475;

double y = 7.22;

double z = x - y;

System.out.println("x - y = " + Math.round(z));

...

I get "x - y = 20", not 20.255. If I do not use Math.round, I get 20.255000000000003. Now, how would one do the basic calculations then and get the correct result?

...

double x = 27.475;

double y = 7.22;

double z = x - y;

System.out.println("x - y = " + Math.round(z));

...

I get "x - y = 20", not 20.255. If I do not use Math.round, I get 20.255000000000003. Now, how would one do the basic calculations then and get the correct result?

Manfred Leonhardt

Ranch Hand

Posts: 1492

posted 15 years ago

Hi Sergey,

You are getting the correct result. Math.round only returns an integer. If you want to "print" out the answer formatted then you can make use of java.text.SimpleDecimalFormat.

SimpleDecimalFormat sdf = new SimpleDecimalFormat( "#.000" );

System.out.println( "x - y = " + sdf.format( z ) );

Regards,

Manfred.

You are getting the correct result. Math.round only returns an integer. If you want to "print" out the answer formatted then you can make use of java.text.SimpleDecimalFormat.

SimpleDecimalFormat sdf = new SimpleDecimalFormat( "#.000" );

System.out.println( "x - y = " + sdf.format( z ) );

Regards,

Manfred.