简体   繁体   中英

Java: What is the right way to convert String into a valid amount of money(BigDecimal)

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,

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.

Did you mean to achieve the following:?

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

Output

$1,000.00

Use new BigDecimal(strValue) .

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

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."

If you want to print decimal with, use setScale method

String amount = "1000";
BigDecimal validAmount = new 
BigDecimal(amount).setScale(2,RoundingMode.CEILING);
System.out.println(validAmount); // prints: 1000.00

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM