Search code examples
javabigdecimal

BigDecimal getting rounded..but i do not want any rounding


In my code i want to insert into db without any rounding or exponentiation ..but it is converted in my java code when i use a sop as 2.631578947368421E-7

Below is the code i use:

BigDecimal a =new BigDecimal(0.0000002631578947368421052631578947368421052632,MathContext.DECIMAL64);
System.out.println(a);

I just want it to be maintained as it is because i want to do some calculations .

Please do provide me an apt solution.


Solution

  • Construct the big decimal using a String, otherwise the constant you enter gets rounded before it is passed as argument to the constructor of BigDecimal.

    So write something like this:

    BigDecimal a =new BigDecimal("0.0000002631578947368421052631578947368421052632");
    System.out.println(a.toPlainString());
    

    And all should work.

    EDIT: you should also get rid of the second argument of the constructor as static MathContext.DECIMAL64 means: A MathContext object with a precision setting matching the IEEE 754R Decimal64 format, 16 digits, and a rounding mode of HALF_EVEN, the IEEE 754R default.

    EDIT2: also use a.toPlainString() when printing to not use scientific notation.