Search code examples
javabigdecimal

can we remove floating zero before decimal point in BigDecimal


BigDecimal bd1= new BigDecimal(0.000);
bd1 = bd1.setScale(2, RoundingMode.HALF_UP).stripTrailingZeros();
System.out.println("bd1 value::"+ bd1);

I get the following 0.00 for bd1, but I want bd1 as .00 not as 0.00. Am I applying the methods correctly?


Solution

  • You can convert the BigDecimal to a String, and then use a regex to conditionally remove the leading zero, if it exists:

    BigDecimal bd1 = new BigDecimal(0.000);
    bd1 = bd1.setScale(2, RoundingMode.HALF_UP).stripTrailingZeros();
    String bdString = bd1.toString().replaceFirst("^0+(?!$)", "")
    System.out.println("bd1 value::"+ bdString);