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?
I was trying to make my own class for currencies using longs, but apparently
Share
Here are a few hints:
BigDecimalfor computations if you need the precision that it offers (Money values often need this).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.NumberFormatclass, use thescale()method on theBigDecimalinstance to set the precision and the rounding method.PS: In case you were wondering,
BigDecimalis always better thandouble, when you have to represent money values in Java.PPS:
Creating
BigDecimalinstancesThis is fairly simple since
BigDecimalprovides constructors to take in primitive values, andStringobjects. You could use those, preferably the one taking theStringobject. For example,Displaying
BigDecimalinstancesYou could use the
setMinimumFractionDigitsandsetMaximumFractionDigitsmethod calls to restrict the amount of data being displayed.