Search code examples
javaseleniumbigdecimal

How to get a value using Bigdecimal mathematical operations in Java


I am trying to get the Tax value of a product (Tax % I am passing as static value)

using the Bigdecimal but getting the error below is my code

        double  dis,amount,s;
        BigDecimal taxprice;




        List<WebElement> firstproductSubtotalprice = getDriver().findElements(By.xpath("//p[@class='m-order-detail-item-name']/span"));
        BigDecimal firstproductSubtotalpricevalue = null;
        for (WebElement webElement : firstproductSubtotalprice) {
            String priceText = webElement.getText();
            if (priceText != null && priceText.length() > 0) {
                firstproductSubtotalpricevalue = new BigDecimal(priceText.replace('$', ' ').trim());
                System.out.println("The First Product Subtotal Price is: "+ firstproductSubtotalpricevalue);
                break;
            }
        }



        List<WebElement> firstproductTaxprice = getDriver().findElements(By.xpath("//span[contains(text(), 'Tax')]/following-sibling::span[1]"));
        BigDecimal firstproductTaxpriceValue = null;
        for (WebElement webElement : firstproductTaxprice) {
            String priceText = webElement.getText();
            if (priceText != null && priceText.length() > 0) {
                firstproductTaxpriceValue = new BigDecimal(priceText.replace('$', ' ').trim());
                System.out.println("The First Product Tax Price is: "+ firstproductTaxpriceValue);
                break;
            }
        }

        taxprice = firstproductSubtotalpricevalue;

        dis=10;

        s=100-dis;

        BigDecimal  c= firstproductTaxpriceValue;


               BigDecimal   a = taxprice.multiply(new BigDecimal(s)); 

               BigDecimal  b =  a.divide(a, 100);



               System.out.println(a+"/"+b+" = "+c);

Using the above code I want to get the tax value and want to compare with the firstproductTaxpriceValue, if the tax amount is equal to firstproductTaxpriceValue then my test cases is pass if not fail.

Please help me to get the tax value


Solution

  • Rounding mode is not provided while dividing.

    Below is the declaration of the method:

    public BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode)
    

    Try this:

     BigDecimal  b =  a.divide(new BigDecimal(100),2,RoundingMode.CEILING);
    

    Where 1st argument, new BigDecimal(100) is the value you want to divide to

    2nd argument,2 is the scale or no. of decimal places

    3rd argument, RoundingMode.CEILING is the mode with which way you want to round the outcome.