# Bookmark: Working with money and currency in Java

Category:

Sooner or later, everyone trying to calculate money in Java discovers that computers can't add. Doesn't Java know how to add two numbers together? Actually, the problem is much older than Java and can be found in the IEEE 754 specification that defines how floating-point numbers work. As at least one software engineer has commented, "floating-point is designed to give you the wrong answer very quickly." This is not far from the truth.

Floating-point numbers are actually made up of three different parts stored in a 32-bit field. The first bit is a sign bit. The next eight bits are the exponent and the remaining twenty-three bits are the significand. The exponent holds the highest power of 2 that is smaller than the number. The remainder is stored in the significand. Let's look at the number 1,000. The highest power of 2 less than 1,000 is 2 to the power of 9, which is 512. We add 127 to 9 (that is so we can store negative exponents without using a sign bit) and store that in the exponent. The remainder of 488 is stored in the significand. The significand is divided into two portions. In our example, the first 9 bits (the size of the exponent) represents the integral portion of the significand and the remaining 14 bits represents the decimal portion.

Tags:
Tags:
Tags:
Tags:
Tags:
Tags:
Tags:
Tags: