20

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 ?

Community
  • 1
  • 1
Łukasz Woźniczka
  • 1,625
  • 3
  • 28
  • 51

6 Answers6

27

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

Paul Sanwald
  • 10,899
  • 6
  • 44
  • 59
7

an integer (or long) for the smallest denomenator you care about (cents for USD and EUR)

this is because floating points on computers are inherently inaccurate for decimal values(0.1+0.2 != 0.3)

you only need to translate between cent and main dollar in the UI while the domain calculates everything in cents

ratchet freak
  • 47,288
  • 5
  • 68
  • 106
4

Personally, I would use BigDecimal (and so does my company!). I consider float or double bad suggestions because of the way floating-point values are stored in the system and there is a possibility of loss of precision (which you certainly don't want when handling money).

asteri
  • 11,402
  • 13
  • 60
  • 84
3

If you're building a financial system, I recommend you create or use your own Java class to represent monetary amounts.

As far as the data type to use to hold a monetary amount, long or BigDecimal.

Here's an example Money class that shows the types of methods you need when working with monetary amounts.

Gilbert Le Blanc
  • 50,182
  • 6
  • 67
  • 111
1

If you use sensible rounding of your results double is works perfectly well and not only the fastest but the simplest to write. This can represent money up to $70 trillion without error. Don't use float as this can only represent up to about $10,000 without error.

If you don't know what sensible rounding to use, BigDecimal or long cents could be a better choice.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

You need to use the BigDecimal class.

Alex
  • 25,147
  • 6
  • 59
  • 55