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

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

问题描述

我试图使用longs为我自己的货币类,但显然我应该使用 BigDecimal 。有人可以帮助我开始吗?对于美元货币使用 BigDecimal s的最佳方法是什么,比如至少但不超过2美分的小数点等等。<$的API c $ c> BigDecimal 很大,我不知道使用哪种方法。此外, BigDecimal 具有更好的精度,但如果它通过 double ,并不是全部丢失?如果我做新的 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 进行计算它提供(Money值通常需要这个)。

  2. 使用 NumberFormat 用于显示的类。本课程将处理不同货币金额的本地化问题。但是,它只会接受基元;因此,如果您因为转换为 double 而接受准确性的微小变化,则可以使用此类。

  3. 使用时 NumberFormat 类,在 BigDecimal scale()方法c>实例设置精度和舍入方法。

  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 对象。您可以使用这些,​​最好是那个字符串对象。例如,

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

您可以使用 setMinimumFractionDigits setMaximumFractionDigits 方法调用以限制显示的数据量。

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天全站免登陆