Possible Duplicate:
Representing Monetary Values in Java
which java type is good to handle price value? and please tell my why ?
I dont know it is simply question :)
I only know that this type must be "safe". Because if we create shop applicatoion or somethink like that.
ps. I need BEST PRACTICE
and how it present in database ?
1 Answer. Java has Currency class that represents the ISO 4217 currency codes. BigDecimal is the best type for representing currency decimal values.
you should use BigDecimal when dealing with currencies. Java's native floating point types suffer from the same precision issues as other languages, since some decimals cannot be accurately represented as floating point numbers.
Unlike the DECIMAL data type, the MONEY data type is always treated as a fixed-point decimal number. The database server defines the data type MONEY(p) as DECIMAL(p,2). If the precision and scale are not specified, the database server defines a MONEY column as DECIMAL(16,2).
The best type for price column should be DECIMAL. The type DECIMAL stores the value precisely. For Example - DECIMAL(10,2) can be used to store price value. It means the total digit will be 10 and two digits will be after decimal point.
you should use BigDecimal when dealing with currencies. Java's native floating point types suffer from the same precision issues as other languages, since some decimals cannot be accurately represented as floating point numbers. Even thought it's not java specific, this is an excellent article which describes the complexities around representing decimal values as floating point numbers.
In general, transient values in your application should always use BigDecimal, only converting to a float when you must (for persistence, or displaying data to a user, etc).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With