Search code examples
javabigdecimal

What's the proper syntax for Java's BigDecimal?


I have two double counters that I'm incrementing based on certain criteria. The counters will increment by either 1 or .01, and the results summed together for a serial number of 1.00, 1.01, 1.02, etc. I'm getting results like 1.01999999999 or 1.111111111111, an expected condition due to the nature of double.

I am trying to use BigDecimal, and although the Java Documentation indicates

BigDecimal(double val)
           Translates a double into a BigDecimal which is the exact decimal representation of the double's binary floating-point value.

I cannot get the code to work.

            ....
if (condition1) {
    indexNo = indexNo + 1;
    subIndexNo = .00;
} else
    if (condition2) {
        subIndexNo = subIndexNo + .01;
    }
recNo = indexNo + subIndexNo;
BigDecimal record = BigDecimal(double recNo);

Error messages from the compiler

C:\pathtojava\sync\java\bin>javac ParseWhiData.java
ParseWhiData.java:97: error: '.class' expected
                                BigDecimal record = BigDecimal(double recNo);
                                                                      ^
ParseWhiData.java:97: error: ';' expected
                                BigDecimal record = BigDecimal(double recNo);
                                                                           ^
2 errors

What am I doing wrong while accessing BigDecimal? What's the proper syntax to convert a double to a Big Demimal, and, most importantly, will it turn 1.019999999999 to 1.02


Solution

  • BigDecimal (and every object in Java) is instantiated via the new operator.

    Also, get rid of the double keyword in the constructor, since you already have defined a variable named recNo.

    Change

    BigDecimal record = BigDecimal(double recNo);
    

    to

    BigDecimal record = new BigDecimal(recNo);