Fundamentals 9 min read

How to Correctly Create and Use BigDecimal in Java for Precise Calculations

BigDecimal provides precise arithmetic in Java, but its correct usage requires understanding its internal unscaled value and scale, avoiding the inaccurate BigDecimal(double) constructor, and preferring String or valueOf methods to accurately represent decimal numbers such as 0.1 in financial and e‑commerce applications.

Full-Stack Internet Architecture
Full-Stack Internet Architecture
Full-Stack Internet Architecture
How to Correctly Create and Use BigDecimal in Java for Precise Calculations

BigDecimal, part of java.math, is widely used for precise arithmetic, especially in financial, payment, and e‑commerce systems, because primitive floating‑point types like double cannot represent many decimal fractions exactly.

The article explains why double is imprecise: computers store numbers in binary, and many decimal fractions (e.g., 0.1) become infinite repeating binary fractions, leading to rounding errors as defined by the IEEE‑754 standard.

BigDecimal achieves precision by representing a number as an unscaled integer value together with a scale (the number of digits to the right of the decimal point). The unscaled value may be stored in a long intCompact or a BigInteger intVal depending on its size.

Key fields of the class are:

private final BigInteger intVal;
private final int scale;
private final transient long intCompact;

The scale() method simply returns the scale field, indicating how many decimal places the number has (zero or positive) or, if negative, how many trailing zeros the value represents.

BigDecimal provides four constructors:

BigDecimal(int)
BigDecimal(double)
BigDecimal(long)
BigDecimal(String)

Using new BigDecimal(double) inherits the inaccuracy of the double argument; for example, new BigDecimal(0.1) actually stores 0.1000000000000000055511151231257827021181583404541015625.

Therefore, to create an exact decimal value, the article recommends using the String constructor or BigDecimal.valueOf(double) , which internally uses Double.toString to obtain a precise representation.

Example of the recommended approaches:

BigDecimal recommend1 = new BigDecimal("0.1");
BigDecimal recommend2 = BigDecimal.valueOf(0.1);

In summary, because binary floating‑point cannot precisely represent many decimal fractions, developers should avoid the BigDecimal(double) constructor and instead use the String constructor or valueOf to ensure accurate calculations.

JavaprogrammingPrecisionBigDecimalFloating Pointfinancial
Full-Stack Internet Architecture
Written by

Full-Stack Internet Architecture

Introducing full-stack Internet architecture technologies centered on Java

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.