Total Pageviews

2014/08/12

java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result

Problem
As I execute the following code snippet
   public static void main(String args[]) {  
     BigDecimal one = new BigDecimal(1);  
     BigDecimal two = new BigDecimal(2);  
     BigDecimal three = new BigDecimal(3);  
     System.out.println(one.divide(two));  
     System.out.println(one.divide(three));  
   }  

The console showed:
0.5  
 Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.  
      at java.math.BigDecimal.divide(BigDecimal.java:1616)  
      at gov.nta.fms.web.rest.Fms421rResource.main(Fms421rResource.java:204)  

Why one.divide(two) is working fine?  But failed to execute one.divide(three) ?

Root Cause
Because I am not specifying a precision and a rounding-mode. 
BigDecimal is complaining that it could use 10, 20, 5000, or infinity decimal places, so it cannot be able to show me the exact representation of the number.

We need to assign its scale and rounding mode, please check the following code snippets:
   public static void main(String args[]) {  
     BigDecimal one = new BigDecimal(1);  
     BigDecimal two = new BigDecimal(2);  
     BigDecimal three = new BigDecimal(3);  
     System.out.println(one.divide(two));  
     System.out.println(one.divide(three, 2, BigDecimal.ROUND_HALF_UP));  
   }  


Here is java doc:
The console showed:
 0.5  
 0.33  

Reference
[1] http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#divide(java.math.BigDecimal,%20int,%20int)

No comments: