// I got these two examples from the internet.
/* I know this is an 'introduction', but Java Doubles are NOT real numbers!
* They are _approximations_ of Real numbers!
* Doubles/Floats should NEVER under any circumstance be used for prices!
* Watch the movie Office Space for an explanation... or try this code at home:
*/
public class DoubleMath {
public static void main(String[] args) {
double maybeOne = .1 * 10;
System.out.println("Does .1 x 10 = 1 in floating point math?");
System.out.println(maybeOne == 1);
System.out.println("Actual Value:" + maybeOne);
maybeOne = .1 + .1 + .1 + .1 + .1 + .1 + .1 + .1 + .1 + .1;
System.out.println("How about if we add .1 ten times?");
System.out.println(maybeOne == 1);
System.out.println("Actual Value:" + maybeOne);
test2();
}
static void test2() {
double x = 1234;
x = x * 0.1;
x = x * 0.1;
System.out.println("\nx should be 12.34, but x actually is " +x);
// a better way is double x = 1234 / 100;
//This reduced the number of arithmetic operations on the double, but rounding can still take place.
}
}
/****************************************
Output:
Does .1 x 10 = 1 in floating point math?
true
Actual Value:1.0
How about if we add .1 ten times?
false
Actual Value:0.9999999999999999
x should be 12.34, but x actually is 12.340000000000002
******************************************/