[英]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字段转换为代表有效金额的BigDecimal字段,例如:
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)? 使用什么样的API将String转换为Java中的有效金额(例如:apache commons library)?
Thanks in advance, 提前致谢,
How about the BigDecimal(String)
constructor? BigDecimal(String)
构造函数怎么样?
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. 如果要以不同方式
Formatter
输出,请使用Formatter
类。
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)
. 使用
new BigDecimal(strValue)
。
Will save you enormous pain and suffering resulting from The Evil BigDecimal Constructor 将为您节省由邪恶BigDecimal构造函数导致的巨大痛苦和痛苦
There is the Joda-Money library for dealing with money values. 有一个Joda-Money库来处理货币价值。 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 如果要打印十进制,请使用setScale方法
String amount = "1000";
BigDecimal validAmount = new
BigDecimal(amount).setScale(2,RoundingMode.CEILING);
System.out.println(validAmount); // prints: 1000.00
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.