Why Float Can’t Accurately Store Money and What to Use Instead
This article explains why using a float to store monetary values leads to precision errors by examining binary representation, demonstrates the problem with a Java example, and recommends using integer or decimal types for accurate financial calculations.
Why Float Can’t Accurately Store Money
Consider the following Java example:
public class FloatTest {
public static void main(String[] args) {
float f1 = 6.6f;
float f2 = 1.3f;
System.out.println(f1 + f2);
}
}The output is 7.8999996 , which differs from the expected 7.9 due to binary floating‑point representation.
Computers operate on binary numbers, so any numeric type is ultimately stored as bits.
Binary Calculation of 6.6 + 1.3
Float Underlying Storage
A float occupies 32 bits: 1 sign bit, 8 exponent bits, and 23 fraction (mantissa) bits.
Binary Conversion
Real numbers are split into an integer part and a fractional part. The integer part is converted to binary in the usual way.
Integer Part: 6
Thus 6 becomes 110 in binary.
Fractional Part
Multiply the fraction by 2, record the integer part, and repeat.
0.6 to Binary
The process yields the repeating pattern 0.10011001… , so 6.6 becomes 110.10011001… .
Normalization
Normalize to have a single leading 1: 1.1010011001 × 2^2 .
Exponent Bias
Bias = 2^(e‑1)‑1, where e is the number of exponent bits (8 for float). Bias = 127. Adding the actual exponent (2) gives 129, which is 10000001 in binary.
Assembling the Float Bits
Sign = 0 (positive), exponent = 10000001, mantissa = first 23 bits of the fraction (10100110011001100110011). The final 32‑bit pattern is 01000000110100110011001100110011 , illustrating why precision is lost.
What Should Be Used to Store Money?
Use int and store the amount in the smallest currency unit (e.g., cents).
Use decimal (MySQL decimal(P,D)) for exact decimal arithmetic. column_name decimal(P,D); Where D is the number of digits after the decimal point and P is the total precision.
Example table creation:
CREATE TABLE `test_decimal` (
`id` int(11) NOT NULL,
`amount` decimal(10,2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;DAO interface (MyBatis):
/**
* @description dao layer
*/
@Repository
public interface TestDecimalDao {
@Select("select * from test_decimal where id = #{id}")
TestDecimal getTestDecimal(int id);
}Test class:
/**
* @description test class
*/
public class TestDecimalDaoTest extends BaseTest {
@Resource
private TestDecimalDao testDecimalDao;
@Test
public void test() {
TestDecimal testDecimal1 = testDecimalDao.getTestDecimal(1);
TestDecimal testDecimal2 = testDecimalDao.getTestDecimal(2);
BigDecimal result = testDecimal1.getAmount().add(testDecimal2.getAmount());
System.out.println(result.floatValue());
}
}JDBC maps decimal to Java BigDecimal. The test prints 7.9 , matching the expected result.
Drawbacks of Using Decimal
Consumes more storage space than floating‑point types for the same range.
Arithmetic operations are slower due to higher computational overhead.
For most financial applications, storing amounts as int (or bigint for larger ranges) in the smallest unit is a practical choice that avoids both floating‑point precision issues and the performance costs of decimal.
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.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
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.
