使用 BigDecimal 处理货币 [英] Using BigDecimal to work with currencies

查看:33
本文介绍了使用 BigDecimal 处理货币的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图为使用多头的货币创建自己的类,但显然我应该使用 BigDecimal 代替.有人可以帮我开始吗?将 BigDecimal 用于美元货币的最佳方法是什么,例如将美分设置为至少但不超过 2 个小数位等.BigDecimal 的 API很大,我不知道该使用哪种方法.另外,BigDecimal 有更好的精度,但是如果它通过一个 double 不是全部丢失了吗?如果我使用 new BigDecimal(24.99),它与使用 double 有何不同?或者我应该使用使用 String 的构造函数来代替?

I was trying to make my own class for currencies using longs, but apparently I should use BigDecimal instead. Could someone help me get started? What would be the best way to use BigDecimals for dollar currencies, like making it at least but no more than 2 decimal places for the cents, etc. The API for BigDecimal is huge, and I don't know which methods to use. Also, BigDecimal has better precision, but isn't that all lost if it passes through a double? if I do new BigDecimal(24.99), how will it be different than using a double? Or should I use the constructor that uses a String instead?

推荐答案

这里有一些提示:

  1. 如果您需要 BigDecimal 提供的精度(货币价值通常需要它),请使用它进行计算.
  2. 使用NumberFormat 类用于显示.本课程将处理不同货币金额的本地化问题.但是,它只会接收原语;因此,如果您可以接受由于转换为 double 而导致的准确性的微小变化,您可以使用这个类.
  3. 使用NumberFormat 类时,请使用BigDecimal 实例上的scale() 方法来设置精度和舍入方法.
  1. Use BigDecimal for computations if you need the precision that it offers (Money values often need this).
  2. Use the NumberFormat class for display. This class will take care of localization issues for amounts in different currencies. However, it will take in only primitives; therefore, if you can accept the small change in accuracy due to transformation to a double, you could use this class.
  3. When using the NumberFormat class, use the scale() method on the BigDecimal instance to set the precision and the rounding method.

PS:如果您想知道,BigDecimal 总是更好比 double,当您必须在 Java 中表示货币价值时.

PS: In case you were wondering, BigDecimal is always better than double, when you have to represent money values in Java.

PPS:

创建BigDecimal 实例

Creating BigDecimal instances

这相当简单,因为BigDecimal 提供构造函数来接收原始值String 对象.你可以使用那些,​​最好使用 String对象.例如,

This is fairly simple since BigDecimal provides constructors to take in primitive values, and String objects. You could use those, preferably the one taking the String object. For example,

BigDecimal modelVal = new BigDecimal("24.455");
BigDecimal displayVal = modelVal.setScale(2, RoundingMode.HALF_EVEN);

显示BigDecimal 实例

Displaying BigDecimal instances

您可以使用 setMinimumFractionDigitssetMaximumFractionDigits 方法调用来限制显示的数据量.

You could use the setMinimumFractionDigits and setMaximumFractionDigits method calls to restrict the amount of data being displayed.

NumberFormat usdCostFormat = NumberFormat.getCurrencyInstance(Locale.US);
usdCostFormat.setMinimumFractionDigits( 1 );
usdCostFormat.setMaximumFractionDigits( 2 );
System.out.println( usdCostFormat.format(displayVal.doubleValue()) );

这篇关于使用 BigDecimal 处理货币的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆