views:

125

answers:

4

Hi, I have to convert an incoming String field into a BigDecimal field that would represent a valid amount of money, for example:

String amount = "1000";

BigDecimal valid_amount = convert(amount);

print(valid_amount.toString())//1000.00

What is the right API to use convert a String into a valid amount of money in Java (eg: apache commons library)?

Thanks in advance,

+5  A: 

How about the BigDecimal(String) constructor?

String amount = "1000";
BigDecimal validAmount = new BigDecimal(amount);
System.out.println(validAmount); // prints: 1000

If you want to format the output differently, use the Formatter class.

Skrud
A: 

Use new BigDecimal(strValue).

Will save you enormous pain and suffering resulting from The Evil BigDecimal Constructor

Marcus
+1  A: 

Did you mean to achieve the following:?

NumberFormat nf = NumberFormat.getCurrencyInstance();
System.out.println(nf.format(new BigDecimal("1000")));

Output

$1,000.00
ring bearer
A: 

There is the Joda-Money library for dealing with money values. But, according to the web site, "the current development release intended for feedback rather than production use."

dave