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

4
  • "the original string could use comma": could or will? Commented Jun 20, 2018 at 8: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 Commented Jun 20, 2018 at 8:21
  • 2
    This answer will help you in this situation: How to parse number string containing commas into an integer in java? Commented Jun 20, 2018 at 8:23
  • Thanks, but it seems to be usefull in case of integer.. Commented Jun 20, 2018 at 8:40

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

@Lorenzo elegant ? You can print flowers around if you want^^
0

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

BigDecimal num = new BigDecimal(rowCell.replace(',', '.'));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.