why when increase floating number with floating number catch error as

for(double i=0; i<10;i+=0.1)
System.out.println(i);

the out put is 0.0
0.1
0.2
0.300004
....ect
but the logicaly output is
0.1
0.2
0.3
....ect

double values tend to do that. I recommend having a method round the double value before printing it, so you only print a certain number of digits after the decimal point. A way I usually like to set the number of decimals is to multiply the double by 10^(number of spots after decimal I want), then casting the double to a temporary int value that truncates the decimal point, and then dividing by 10^(number of spots after decimal I want) and storing that in the double value. For example:

double d = 45.6778234; //I only want 2 decimal points after this.
int temp = (int)(10^2*d); //temp will contain 4567.
d = (0.0+temp) / (10^2); //the 0.0 is to be sure that the division is precise.  This will store 45.67 in d.

NOTE: I USED THE CARROT NOTATION TO SYMBOLIZE RAISING TO A POWER -- to do this yourself you should look into the Math class or design a method on your own to accomplish this goal. The carrot notation does not work here in java -- that is calculator notation only. You will need to modify the code I have there so that the powers are correctly calculated -- this is just a basic algorithm.

Or this

double val = .2;
val += .1;
System.out.printf("%.2f", val);

>.< I hate printf it confuses me

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.