I need to read data from a JSON and there are some money data as shown below:
$234,205,860
I thought to map this data to my DTO class as String, but I am not sure if there is a proper data type in Java. I look at on the web, but could not see any for this kind of data.
So, is there any data type for this money value? Or should I use String to keep this kind of data in Java?
CodePudding user response:
Precision is the keyword here. Long and float are a bad choice in most cases! To not lose precision, String could come to mind and would work for storing values nicely without running into issues ruining precision.
If you need to manipulate values in the future go for BigDecimal. What data type to use for money in Java?
CodePudding user response:
Assuming you want to cope with multiple currencies, you should create a class that holds both the currency value and units (dollars, pounds, riyals, etc).
For the value, you could use a scaled long
(i.e. store cents, or whatever the smallest unit is) and scale the numbers for input/output. That works only if you are sure the value of cents (or smallest unit) is always less than 263-1 or 9,223,372,036,854,775,807, including any intermediate results of calculations. If you don't want to worry about potential overflow, BigDecimal
is the way to go.
For the units, there's a java.util.Currency
class, but it may or may not meet your needs.
Why NEVER to use floating point for currency: