Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 57 / 68

Watch Out for Floating-Point Rounding Errors

In this lesson you will learn about the error computers introduce when handling decimals, and what to watch for in monetary calculations. This is for anyone searching for "PHP floating point error".

Computers represent decimals in binary, so even a straightforward calculation such as 0.1 + 0.2 may not land exactly on 0.3. PHP rounds it to 0.3 for display, but an internal comparison still comes back false because of the error.

The sample code shows that printing 0.1 + 0.2 looks like 0.3, yet var_dump(0.1 + 0.2 == 0.3) reports bool(false). Note the gap between the rounded display and the exact internal value.

A common stumbling block for beginners is not noticing this error at all and comparing decimals for equality directly. Where the error matters - monetary calculations, for instance - you need a workaround such as calculating in integers (in cents).

This is not specific to PHP; it comes from how computers work and applies to most programming languages. In accounting systems and anywhere precision is required, allowing for it is essential.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)