views:

56

answers:

2

What is the maximum number of digits we can have after the decimal point of a BigDecimal value in Java?

+4  A: 

It's (almost) unlimited. You can store roughly 2 billion digits after the decimal point if scale is set to the maximum value of an integer, although you may run out of memory if you try to do this. If you need to store so many digits that the limit is a problem then you probably need to rethink the design of your program.

See the BigDecimal documentation:

Immutable, arbitrary-precision signed decimal numbers. A BigDecimal consists of an arbitrary precision integer unscaled value and a 32-bit integer scale. If zero or positive, the scale is the number of digits to the right of the decimal point. If negative, the unscaled value of the number is multiplied by ten to the power of the negation of the scale. The value of the number represented by the BigDecimal is therefore (unscaledValue × 10-scale).

Mark Byers
+1  A: 

According to what is mentioned in the BigDecimal Java 2 Platform Standard Ed. 5.0:

Immutable, arbitrary-precision signed decimal numbers. A BigDecimal consists of an arbitrary precision integer unscaled value and a 32-bit integer scale. If zero or positive, the scale is the number of digits to the right of the decimal point. If negative, the unscaled value of the number is multiplied by ten to the power of the negation of the scale. The value of the number represented by the BigDecimal is therefore (unscaledValue × 10^(-scale)).

According to Java's implementation of 32-bit integers:

int: The int data type is a 32-bit signed two's complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). For integral values, this data type is generally the default choice unless there is a reason (like the above) to choose something else. This data type will most likely be large enough for the numbers your program will use, but if you need a wider range of values, use long instead.

This means that for zero or positive scale numbers you have 2,147,483,647 digits to the right of the decimal point. For negative scale numbers, you have unscaledValue shifted to the right of the decimal point by 2,147,483,648 digits.

Luis Miguel