Why Java’s Float and Double Lose Precision and How BigDecimal Fixes It
This article explains how floating‑point calculations in Java can lose precision, especially for monetary values, and demonstrates using the BigDecimal class—particularly its String constructor—to achieve exact arithmetic in backend applications.
We all know that floating‑point variables lose precision during calculations. The article shows a Java example where adding 0.05 and 0.01 yields 0.060000000000000005, illustrating the problem for monetary calculations.
Float has 6‑7 significant digits, double 15‑16. To avoid such errors, Java’s BigDecimal class is recommended.
API
Constructors:
BigDecimal(int) // from int
BigDecimal(double) // from double (may lose precision)
BigDecimal(long) // from long
BigDecimal(String) // from string (exact)Methods:
add(BigDecimal) // addition
subtract(BigDecimal) // subtraction
multiply(BigDecimal) // multiplication
divide(BigDecimal) // division
toString()
doubleValue()
floatValue()
longValue()
intValue()Even BigDecimal(double) can lose precision, as shown by a demo where constructing from double yields 2.030000000000000026645… while using the String constructor yields the exact 2.03.
The JDK source notes that the double constructor’s result is unpredictable because many decimal fractions cannot be represented exactly in binary. The recommended way is to convert the double to a string first or use BigDecimal.valueOf(double).
Correct Usage
Since BigDecimal objects are immutable, arithmetic operators cannot be used; you must call the provided methods with other BigDecimal instances.
A utility class BigDecimalUtil is presented, offering static methods add, sub, mul, and div that accept double arguments, convert them to BigDecimal via Double.toString, and perform precise operations.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
