Skip to content

Round double after cast from String

While happily coding on my genetic algorithm framework, a weird thing occurred when parsing doubles from strings.
Java has trouble with the exact presentation of numeric values such as 0.1, 0.02 in a binary floating-point number. It will try to near down the exact presentation and usually ends up with 0.09999999, 0.020000001 and so on.
Of course 0.1 is not 0.09999999, so we need to somehow round this value to 0.1 again.
I have coded a little fragment to do exactly that, and I want to share it with you (I couldn't find a valid solution on the net):

int d_str="0.01";
double d=Double.valueOf(d_str);
// amount of decimals
int d_length = Double.valueOf(d-(int)d).toString().length()-2;
int temp = (int) (Math.round(d * Math.pow(10, d_length)));
double final_d=(double) temp) / Math.pow(10, d_length);