Here are a few hints:
- Use
BigDecimalfor computations if you need the precision that it offers (Money values often need this). - Use the
NumberFormatclass 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
NumberFormatclass, use thescale()method on theBigDecimalinstance to set the precision and the rounding method.
PS: In case you were wondering, BigDecimal is always better than double, when you have to represent money values in Java.
PPS:
Creating BigDecimal instances
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);
Displaying BigDecimal instances
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()) );