Search code examples
javastringtype-conversionformatbigdecimal

Java Convert String into BigDecimal


I have to convert a String (read from excel cell) into BigDecimal, but I have to consider :

  • the BigDecimal number will have two decimal digits, so I must form it in that way
  • the original string could use comma (",") as decimal separator (and this is my greater problem because if I write BigDecimal num = new BigDecimal(rowCell); and rowCell has comma as decimal separator I will take an exception...)

Could you help me? Thank you in advance


Solution

  • You need to do it by steps:

    • replace the comma , by a dot .
    • get a BigDecimal from this new string
    • round it to 2 decimals with ROUND_DOWN or ROUND_UP

    String str = "123,456";                   // String 132,456
    str = str.replace(',', '.');              // String 132.456
    BigDecimal b = new BigDecimal(str);       // BigDec 132.456
    b = b.setScale(2, BigDecimal.ROUND_DOWN); // BigDec 132.45
    

    If you concat you have :

    String str = "123,456";                  
    BigDecimal b = new BigDecimal(str.replace(',', '.')).setScale(2, BigDecimal.ROUND_DOWN);   
    

    Working DEMO