trouble data type conversion

I have written a function and want the expect result written in the comment. but the result is not as expected, why?

int genNextUGRPK(int a){

// Expect result: input 63001 output 64001, input 15001 output 16001

Integer A = new Integer(a);

String StrA = A.toString();

int lenA = StrA.length();

double factor = Math.pow(10, lenA - 1);

double doubleA = (((double)a / factor)+ 0.1) * factor; //return 64000.99999....

a = new Double(doubleA).intValue();

return a;

}

[536 byte] By [tong123123a] at [2007-11-27 2:06:16]
# 1
my input is 63001, but the output is 64000, not 64001 as expected!!
tong123123a at 2007-7-12 1:53:12 > top of Java-index,Java Essentials,New To Java...
# 2
If the input is 63001, the output of your program is 64000. But your expected result is 64001.This is because you used "intValue()'. Which will return the integer portion of the input.So, the output is 64000 instead of 64000.999999.
Vencya at 2007-7-12 1:53:12 > top of Java-index,Java Essentials,New To Java...
# 3
no, the key problem is why 6.3001 + 0.1 = 6.400999999......, not 6.4001?
tong123123a at 2007-7-12 1:53:12 > top of Java-index,Java Essentials,New To Java...
# 4
I have tested a simple statementdouble test = 6.3001d + 0.1d;the result is also 6.40099999999...., not 6.4001, why?anyone can help?
tong123123a at 2007-7-12 1:53:12 > top of Java-index,Java Essentials,New To Java...
# 5

a = new Double(doubleA).intValue();

to

a = (int) Math.round(doubleA);

Does this solve your problem ?

Correct me if I am wrong.

Number representation in Java is in binary form.

10.011 is representing

1 * (2^1) + 0 * (2^0) + 0 * (2^-1) +10 * (2^-2) + 1 * (2^-3)

= 2 + 025 + 0.125

= 2.375

To represent 0.1, it is actually summing some decimal numbers together.

rym82a at 2007-7-12 1:53:12 > top of Java-index,Java Essentials,New To Java...
# 6

Your using the data type 'double', which represents precesion upto 15 digits after the decimal value. So, the result would be 64000.99999.

In order to display 64001, use round() of Math.

"Math.round(doubleA);"

which will solve the problem and your statement is:

[ (double)a / factor)+ 0.1) * factor] not [(double)a / factor)+ 0.1)]. So, it will display 64000.9999 not 6.400000....

Vencya at 2007-7-12 1:53:12 > top of Java-index,Java Essentials,New To Java...