Search code examples
javabigdecimal

pass bigdecimal numbers in java


I want to pass value to a method using big decimal number but my program shows compiler errors.

package com.khalidFarik;

import java.math.BigDecimal;

public class Main {
    public static void main(String[] args) {
        checknumbersinDecimals(12.3,12.2);
    }

    public static void checknumbersinDecimals(BigDecimal payment1,BigDecimal payment2){
        payment1 = new BigDecimal("1230.23");
        payment2 = new BigDecimal("1230.23");
        BigDecimal number3= payment1.subtract(payment2);
        System.out.println(number3.toString());
    }
}

How can I pass the big decimal number to my method checknumbersinDecimals() in the main method?


Solution

  • You method accepts BigDecimal as args, but you are passing 12.3,12.2 - which are double and not BigDecimal.

    You pass BigDecimal objects as param instead of double as follows:

    checknumbersinDecimals(new BigDecimal(String.valueOf(12.3)),new BigDecimal(String.valueOf(12.2)));
    

    Note: use BigDecimal(String) constructor instead of BigDecimal(double) constructor as by using the latter, you could lose precision. The caution as rightly mentioned in the doc:

    • The results of this constructor can be somewhat unpredictable. One might assume that writing new BigDecimal(0.1) in Java creates a BigDecimal which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625. This is because 0.1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length). Thus, the value that is being passed in to the constructor is not exactly equal to 0.1, appearances notwithstanding.
    • The String constructor, on the other hand, is perfectly predictable: writing new BigDecimal("0.1") creates a BigDecimal which is exactly equal to 0.1, as one would expect. Therefore, it is generally recommended that the String constructor be used in preference to this one.
    • When a double must be used as a source for a BigDecimal, note that this constructor provides an exact conversion; it does not give the same result as converting the double to a String using the Double.toString(double) method and then using the BigDecimal(String) constructor. To get that result, use the static valueOf(double) method.