devxlogo

Floating point accuracy

Question:
When I do the following,

double answer = 121 * .1;System.out.println("Answer: " + answer);

I get,

Answer: 12.100000000000001

What’s going on?

Answer:
Almost every computer architecture represents numbers in binary format, also known as base 2. Java’s virtual machine is no exception and follows the IEEE binary floating point standard. It is not possible to represent exactly all floating point numbers in base 2 (or base 10, for that matter). The base 10 decimal number 0.1 is one such number. You should assume that every floating point operation will contain some small error and account for it by comparing numbers witha tolerance value representing the amount of error you are willing to accept.

Charlie has over a decade of experience in website administration and technology management. As the site admin, he oversees all technical aspects of running a high-traffic online platform, ensuring optimal performance, security, and user experience.

See also  Five Early Architecture Decisions That Quietly Get Expensive

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.