Search code examples
javaroundingcurrencybigdecimal

For java applications, is it safe to use BigDecimal when dealing with money, or should I use integers and create an abstraction for money?


It's been awhile since I've wrote applications that dealt with money. Many years ago, I would make a money object that dealt with Integers behind the scenes. Whenever the amount was printed somewhere, it would simply put the decimal place in the correct spot. This was to prevent decimal problems.

Do I still need to do this, or can I just use BigDecimal? What is considered the best practice right now?


Solution

  • It depends on your requirements. You may only have a need for resolution to the nearest K (for example, salary requirements on a job posting website.)

    Assuming you mean you need granularity, BigDecimal seems perfectly suited for the job. It seems certainly "safe" to use, but without knowing exactly what you plan to do with it, it's hard to say for certain.