1

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

azro
  • 53,056
  • 7
  • 34
  • 70
Raul
  • 115
  • 5
  • 16
  • `"the original string could use comma"`: **could** or **will**? – ernest_k Jun 20 '18 at 08:17
  • "Could". Because some users will use dot but I must be able to predict the use of the comma. Thank yuo for the help – Raul Jun 20 '18 at 08:21
  • 2
    This answer will help you in this situation: [How to parse number string containing commas into an integer in java?](https://stackoverflow.com/questions/11973383/how-to-parse-number-string-containing-commas-into-an-integer-in-java) – Sandeep Kokate Jun 20 '18 at 08:23
  • Thanks, but it seems to be usefull in case of integer.. – Raul Jun 20 '18 at 08:40

2 Answers2

2

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

azro
  • 53,056
  • 7
  • 34
  • 70
0

Just replace a comma with a dot. It's simple and fast enough.

BigDecimal num = new BigDecimal(rowCell.replace(',', '.'));
Vitalii Vitrenko
  • 9,763
  • 4
  • 43
  • 62