ãã¤ãããã¾ã§ãã
åãé¸ã¶ã¨ããã®ã¯ããã°ã©ãã³ã°ã®åºç¤ä¸ã®åºç¤ã§ããã以å¤ã«éçºã®ç¾å ´ã§ã注æãå¿ è¦ãªã®ããfloatã¨doubleã®ç²¾åº¦ã®åé¡ãããã¾ãããããããå½ç¶ã¨æã£ã¦ããã®ã§ãããæè¿ããè³ã«ãã¾ãã®ã§ãããã¦è¨åw
ãããã®åã®ç®çãç§å¦æè¡è¨ç®ã®ããã®ç¨éãå¤å°èª¤å·®ãçãã¦ãé«éã«æ¼ç®ããããã¨ãç®çã¨ãã¦ãã¾ããã°ã©ãã£ãã¯ãªã©ã®æç»ç³»ã¨ãã§ãããã
ãã®ããã«ãfloatåãdoubleåã¯èª¤å·®ãå«ãå¯è½æ§ããããããç§å¦ã»å·¥å¦è¨ç®ã§å¤å°ã®èª¤å·®ã¯è¨±å®¹ã§ããå ´åã¯ããã®ã§ãããéèã»ä¼è¨åéã®ããã«æ£ç¢ºãªå¤ãè¦æ±ãããè¨ç®ã«ã¯åãã¾ããã
ã©ããã¦ãæ£ç¢ºãªå¤ã欲ããå ´åã¯ãBigDecimalã¯ã©ã¹ã使ç¨ãããã¨ã«ãªãã¾ããåºæ¬ãã¼ã¿åã®doubleãfloatã¨æ¯è¼ããã¨ä¸ä¾¿ãã¤ä½éã§ããã精度ãä¿è¨¼ããã¦ããã丸ãæ¹ãæå®ã§ãã¾ãã
ããã§è¨åããã¦ããããã«ããéãä¼è¨ãªã©ã®æ£ç¢ºæ§ãåãããè¨ç®ã§ã¯ä½¿ãã¾ãããåºæ¬çã«BigDecimalãå©ç¨ããªãã¨ããã¾ãããã(æ¡æ°ã«ãã£ã¦ã¯intãlongãæ´æ°é¨ã¨å°æ°é¨ã«åãã¦æ¼ç®ããæ¹æ³ãèãããã¾ãããã°ãé¢åã§ãwâåéãã§ããw å¤å°æ¼ç®é度ãé
ãã¨ãBigDecimalãããã§ãwï¼
ãªã®ã§ãå°æ°ç¹ãè¨ç®ãããããã®å¤æ°ã¯floatããdobuleããªã¨ããå®æãªèãã¯ãããªãã®ã§ããç®çã«å¿ããåãé¸ã¶ãã¨ãéè¦ã
ãã¨ãã°ãEfficetive Javaã§ãç»å ´ãããã®å¼ãå½ç¶ããã§ã¯èª¤å·®ãçºçãã¾ãã
System.out.println(1.00-9*.10);
ç§ã®ç°å¢ã§ãã®ãããªçµæã«ãªãã¾ããã
0.09999999999999998
次ã¯BigDecimalã®ä¾ã
ã¡ãã£ã¨ã³ã¼ããé¢åãªæãã«ãªã£ã¦ãã¾ããw
// 1.0 - 9 * 0.1 BigDecimal b1 = new BigDecimal(1.0); BigDecimal b2 = new BigDecimal(-9); BigDecimal b3 = new BigDecimal("0.1"); BigDecimal result = b1.add(b2.multiply(b3)); System.out.println(result.toString());
ã§ããçµæã¯æå¾ ã©ããã§ãã
0.1
0.1ã®é¨åã ããæåå表ç¾ã§ãããããã¯ç²¾åº¦ãè½ã¡ãªãããã«æååã§åæåãã¦ãã¾ããæ°å¤ã§æ¸¡ãã¨èª¤å·®ãçºçããã®ã§æ°ãã¤ããã
BigDecimal b3 = new BigDecimal("0.1");
詳ããã¯ãã¡ãã
doubleããBigDecimalãªãã¸ã§ã¯ããä½æããå ´åã
BigDecimal bd = new BigDecimal(doubleVal);
ã¨ãã¦ãã¾ãã¨ãæµ®åå°æ°ç¹ã§æ£ç¢ºã«è¡¨ããªãæ°å¤ã®å ´åãæå¾ çµæã¨ãºã¬ãå ´åãããã¾ãã
å°æ°ç¹ä»¥ä¸ã¾ã§ãã£ã¡ãè¨ç®ããªãã¨ãããªãç¨éã§ã¯BigDecimalã¨ãããã¨ã§ã
ééã£ã¦ããfloatãdoubleã§ãéã®è¨ç®ããã¦ããã¦ãçºçãããã®èª¤å·®ã調æ´ãããããªãã¸ãã¯ã¯æ¸ãã¦ã¯ããã¾ãããã
追è¨:
Effective Java åç 31é
ã第äºç 48é
ã«äºä¾ã®ç´¹ä»ãããã¾ãã