Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java best type to hold price [duplicate]

Tags:

java

types

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 ?

like image 946
Łukasz Woźniczka Avatar asked Sep 19 '12 14:09

Łukasz Woźniczka


People also ask

What is the best data type to use for money in Java?

1 Answer. Java has Currency class that represents the ISO 4217 currency codes. BigDecimal is the best type for representing currency decimal values.

What data type should be price in Java?

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.

What data type should be used for money?

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).

What would be a good data type to store prices for an international shopping?

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.


1 Answers

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).

like image 88
Paul Sanwald Avatar answered Sep 22 '22 17:09

Paul Sanwald