问题描述
我试图使用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 BigDecimal
s 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?
推荐答案
以下是一些提示:
- 如果需要精度,请使用
BigDecimal
进行计算它提供(Money值通常需要这个)。 - 使用用于显示的类。本课程将处理不同货币金额的本地化问题。但是,它只会接受基元;因此,如果您因为转换为
double
而接受准确性的微小变化,则可以使用此类。 - 使用时
NumberFormat
类,在BigDecimal $ c $上使用
scale()
方法c>实例设置精度和舍入方法。
- Use
BigDecimal
for computations if you need the precision that it offers (Money values often need this). - 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 adouble
, you could use this class. - When using the
NumberFormat
class, use thescale()
method on theBigDecimal
instance to set the precision and the rounding method.
PS:如果你想知道,时。
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
这很简单,因为,以及 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处理货币的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!