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;
}
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.
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....