0

I am facing problem in big decimal no. Following code snippet will explain my problem:

 BigDecimal parsedValue = (BigDecimal) decimalFormat.parse(input);

Here input is a string type. Now suppose value of input is 135abc24 in this case value of parsedValue is 135 but i want to check for such inputs and give an error instead of truncating the string and rest of part. Just want to add input string may also contains exponential nos, so i cant even check for only numeric strings. Please let me know if you want further information or or question is not clear,

Thanks in advance.

skaffman
  • 398,947
  • 96
  • 818
  • 769
Harry
  • 75
  • 2
  • 10

2 Answers2

6

You can use BigDecimal's String constructor to create the BigDecimal (see the link for details) and apply any transformations you wish to your input string beforehands. The constructor throws a NumberFormatException if the input is not a valid representation.

Jens Hoffmann
  • 6,699
  • 2
  • 25
  • 31
  • Hi Jens, Thanks for your reply. Got the desired results. Wanted to vote up but don't have 15 reputation :( Anyways thank a lot. – Harry Nov 29 '10 at 11:54
2

According to the documentation, DecimalFormat.parse() supports a second argument in the form of a ParsePosition reference, which is updated with the position at which the parsing stopped. You can then compare that to the beginning of your string, and determine if the entire string was accepted or not.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • Hi Unwind, Thanks you for your reply. I did not tried this option as I got the desired result with Jens answer. But I will give a try to this and will definitely update here. Thanks! – Harry Nov 29 '10 at 11:59
  • Yeah that's another option to solve the problem. Was going through the old questions n found my comment. better late than never :) – Harry Sep 03 '12 at 10:12