-1

I'm trying to represent money with a datatype in Java. There's a condition though: the money will always be a whole number (eg. $500, $10000000). The choices I thought of are:

  • Double: Faster than the other choices available. That said, will there be a loss of precision? Also, is a double enough to represent any amount of money? I mean, money can get pretty large, so is a double enough to store all such values?
  • BigInteger: The upside here is that there's no limit as such, and obviously no loss of precision. That said, the speed of computations could take a hit.
  • Which one should I use?

    EDIT: This is not a duplicate and is different in that I need to use only whole numbers for money, which brings the question of precision and suitability!

    Community
    • 1
    • 1
    Mathguy
    • 157
    • 11

    1 Answers1

    1

    Do not use double. As you are aware, floating point calculations can result in a loss of precision.

    BigInteger would work, but it is a reference type which makes it more awkward to use.

    Use long. The maximum value is 9223372036854775807 which is likely to be large enough for practical purposes.

    Paul Boddington
    • 37,127
    • 10
    • 65
    • 116
    • Only just large enough. Cobol has 18 decimal digits of visible precision, plus enough extra for correct rounding. And fractions, which `long` doesn't have. And scaling. `BigDecimal` has all this. – user207421 Oct 08 '15 at 04:40
    • @EJP The OP only required integers, so assuming `Long.MAX_VALUE` is big enough for their needs, this is the best solution in terms of convenience and performance for them. However I wouldn't normally recommend `long` for calculations involving money. – Paul Boddington Oct 08 '15 at 04:54
    • @PaulBoddington why not long, though? – Mathguy Oct 08 '15 at 06:31