The maximum value of:
Float
is Float.MAX_VALUE
, (2-2^23)*2^127, something like 3.40282346638528860e+38 or 340,282,346,638,528,860,000,000,000,000,000,000,000.000000.
Long
is Long.MAX_VALUE
, 2^63-1, or 9,223,372,036,854,776,000.
Just what kind of shopping business are you running that does not fit in those types?
Floating-point
Actually, you do not want Float
for the simple reason that it is based on floating-point technology, and you never use floating-point for money. Never use floating-point for any context where accuracy is important. Floating-point trades away accuracy for speed of execution. Usually, your customers will care about money. So you would never use the float
, Float
, double
, or Double
types in Java for such purposes. This workaround is prone to confusion and mistakes obviously, so it requires careful documentation and coding.
BigDecimal
Where accuracy matters, such as money, use BigDecimal
. Not because it can handle large numbers, but because it is accurate. Slow, but accurate.
The advice to use BigDecimal
applies only where you have a fractional amount such as tracking the pennies on a dollar. If you are using only integer numbers, you have no need for BigDecimal
.
Integer workaround for fractional amounts
Indeed a workaround for the floating-point problem in languages lacking an alternative like BigDecimal
is to multiple all fractional amounts until they become integers. For example, if doing bookkeeping to the penny on a dollar (United States), then multiple all amounts by 100 to keep a count of whole pennies as an integer rather than a count of fractional dollars.
Integers
As for working with integer numbers in Java, you have multiple simple choices.
- For numbers 127 and less, use
byte
or Byte
, using 8 bits.
- For numbers 32,767 and less, use
short
or Short
, using 16 bits.
- For numbers 2^31-1 and less (about 2 billion), use
int
or Integer
, using 32 bits.
- For numbers 2^63-1 and less (about umpteen gazillion), use
long
or Long
, using 64 bits.
- For even larger numbers, use
BigInteger
.
Generally best to use the smallest integer type that can comfortably fit your current values as well as fit foreseeable future values.
The 32-bit or 64-bit types are your main choices for modern hardware. You needn't worry about the smallest types unless working with massive amounts of these values, or are quite constrained on memory. And using BigInteger
is overkill for most any business-oriented app. (Science and engineering apps might be a different story.)
See also the Answer by i.merkurev on the JSR 354: Money and Currency API library.