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 mo开发者_运维知识库ney, 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
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
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."
精彩评论