Java:将字符串转换为有效金额的正确方法是什么(BigDecimal)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2603167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 22:00:03  来源:igfitidea点击:

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

javabigdecimal

提问by Midnight Blue

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)?

使用 Java 将字符串转换为有效金额的正确 API 是什么(例如:apache commons 库)?

Thanks in advance,

提前致谢,

回答by Skrud

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

如果要以不同方式格式化输出,请使用Formatter该类。

回答by ring bearer

Did you mean to achieve the following:?

您的意思是要实现以下目标:?

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

Output

输出

,000.00

回答by leedm777

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

有用于处理货币价值的Joda-Money库。但是,根据该网站的说法,“当前的开发版本旨在用于反馈而不是生产用途。”

回答by Tomas Pinto

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

回答by Marcus Leon

Use new BigDecimal(strValue).

使用new BigDecimal(strValue).

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

将为您节省由邪恶的 BigDecimal 构造函数带来的巨大痛苦和痛苦