1
1
package org .geekbang .time .commonmistakes .numeralcalculations .dangerousdouble ;
2
2
3
3
4
+ import lombok .extern .slf4j .Slf4j ;
5
+
4
6
import java .math .BigDecimal ;
5
7
8
+ @ Slf4j
6
9
public class CommonMistakesApplication {
7
10
8
11
public static void main (String [] args ) {
9
-
10
- test ();
12
+ testScale ();
11
13
System .out .println ("wrong1" );
12
14
wrong1 ();
13
15
System .out .println ("wrong2" );
@@ -30,10 +32,22 @@ private static void wrong1() {
30
32
System .out .println ("OK" );
31
33
}
32
34
33
- private static void test () {
34
- System .out .println (Long .toBinaryString (Double .doubleToRawLongBits (0.1 )));
35
- System .out .println (Long .toBinaryString (Double .doubleToRawLongBits (0.2 )));
35
+ private static void testScale () {
36
+ BigDecimal bigDecimal1 = new BigDecimal ("100" );
37
+ BigDecimal bigDecimal2 = new BigDecimal (String .valueOf (100d ));
38
+ BigDecimal bigDecimal3 = new BigDecimal (String .valueOf (100 ));
39
+ BigDecimal bigDecimal4 = BigDecimal .valueOf (100d );
40
+ BigDecimal bigDecimal5 = new BigDecimal (Double .toString (100d ));
41
+
42
+ print (bigDecimal1 );
43
+ print (bigDecimal2 );
44
+ print (bigDecimal3 );
45
+ print (bigDecimal4 );
46
+ print (bigDecimal5 );
47
+ }
36
48
49
+ private static void print (BigDecimal bigDecimal ) {
50
+ log .info ("scale {} precision {} result {}" , bigDecimal .scale (), bigDecimal .precision (), bigDecimal .multiply (new BigDecimal ("4.015" )));
37
51
}
38
52
39
53
private static void wrong2 () {
@@ -49,9 +63,6 @@ private static void right() {
49
63
System .out .println (new BigDecimal ("4.015" ).multiply (new BigDecimal ("100" )));
50
64
System .out .println (new BigDecimal ("123.3" ).divide (new BigDecimal ("100" )));
51
65
52
- System .out .println (new BigDecimal ("4.015" ).multiply (new BigDecimal (Double .toString (100 ))));
53
- System .out .println (new BigDecimal ("4.015" ).multiply (BigDecimal .valueOf (100 )));
54
-
55
66
}
56
67
}
57
68
0 commit comments