0

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

3
Contributors
4
Replies
5
Views
7 Years
Discussion Span
Last Post by kvass
0

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.

Edited by kvass: n/a

1

Or this

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

Edited by BestJewSinceJC: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.