Search code examples
javajava-8doublebigdecimal

Java Double to BigDecimal Conversion Without E Notation


In JDK8:

   import java.math.BigDecimal;
    public class HelloWorld{
    
         public static void main(String []args){
             Double aDouble=new Double(295699630);
            System.out.println(BigDecimal.valueOf(aDouble.doubleValue()));
           
         }
    }

Gives Output: 2.9569963E+8 . Number ends with zero (like 295699630,848436700) comes with notation E. But if number ends with any non zero number then the above code snippet gives us desired output (Number like: 295699631 will not contain 'E' after conversion). What is reason of this & how we can avoid scientic notation 'E' in this conversion? Need output in BigDecimal format (Not String) without 'E' notation. Any help will be appreciated. Thanks in advance.


Solution

  • We can use setScale method for avoiding scientific notation 'E' during conversion from Double to BigDecimal. Follow the below code snippet:

    import java.math.BigDecimal;
        
     import org.apache.commons.lang3.math.NumberUtils;
        
        public class test {
        
            public static void main(String[] args) {
                Double aDouble = NumberUtils.createDouble("345444330");
                System.out.println(BigDecimal.valueOf(aDouble.doubleValue()));//Output:3.4544433E+8
                BigDecimal b = new BigDecimal(aDouble).setScale(2);//Output:345444330.00 
                System.out.println(b);
        
            }
        
        }