There is such a puzzle: three people stay in a hotel, said her 30 yuan to pay after they went in, the wife remembered today is special 25 yuan, 5 yuan to take the man called back three customers, the man hid $ 2 to of their $ 3, so that each of them was $ 1, that is paid 9 yuan per person, and that 3 * 9 = 27, plus $ 2 Tibetan man, equal to 29 yuan, 1 yuan that there where Qula?
Many people doubt quite a long time, that the rest of the dollar in the end gone? We analyze the role:
Boss: Real get 25 yuan
Man: take-2 yuan
Customer: pay the cost of 3 * 9 = 27
27 = 25 + 2 costs and benefits are balanced. The above is mainly confused logic.
But in java development, your money might accidentally lose Oh, look at that!
public class TestFloatDouble {
public static void main(String[] args) {
System.out.println(0.05f+0.01f);
System.out.println(1.0f-0.42f);
System.out.println(4.015d*100);
System.out.println(123.3d/100);
}
}
Guess dialogue, there are prizes! Haha
0.060000002
0.58000004
401.49999999999994
1.2329999999999999
We found that when using floating point type float or double calculates, data may be distorted. Above it is the reason?
We know that the computer does not recognize any data other than binary data. In order to be recognized by the computer after no matter what we use programming language, compiler environment under which to work, we must first translate the source code into binary machine code. To the case mentioned above, for example, we have to verify
public class TestFloatDouble {
public static void main(String[] args) {
System.out.println(Float.toHexString(0.05f));
System.out.println(Float.toHexString(0.01f));
System.out.println(Float.toHexString(1.0f));
System.out.println(Float.toHexString(0.42f));
System.out.println(Double.toHexString(4.015d));
System.out.println(Double.toHexString(123.3d));
System.out.println(0.05f+0.01f);
System.out.println(1.0f-0.42f);
System.out.println(4.015d*100);
System.out.println(123.3d/100);
}
}
As a result:
0x1.47ae14p-7
0x1.0p0
0x1.ae147ap-2
0x1.00f5c28f5c28fp2
0x1.ed33333333333p6
0.060000002
0.58000004
401.49999999999994
1.2329999999999999
Where: ox hexadecimal
p represents the index, which is the base 2
It should not be difficult to understand.
In short, precise answers where needed, to avoid the use of float and double; for currency, to use int, long or BigDecimal.
References:
【1】https://blog.csdn.net/aya19880214/article/details/45891581