Floating Dangers in PHP

Are you working with currencies? Do you use floats? You have to be extremely careful. Check out why.

.com software
2 min readOct 4, 2022
Photo by Mika Baumeister on Unsplash

Do you use floating point numbers to store the currency in your applications? Don’t do that. You are asking for trouble. If you decide to stick to floats, you have to be vigilant — at all times.

How about a simple 0.1 + 0.2 math operation. What can go wrong, right? Due to the nature of how binary numbers are stored internally, it is not possible to represent a fractional number without a precision loss (* except for halves).

Via Reddit

Try running the code below:

Can you guess the output? It’s not so obvious:

float(0.100000000000000005551115123126) float(0.200000000000000011102230246252) float(0.299999999999999988897769753748) float(0.400000000000000022204460492503)
float(0.5)
float(0.599999999999999977795539507497)…

--

--

.com software

Father • PHP developer • entrepreneur • working for a €1bn unicorn startup as a backend engineer >>> https://bit.ly/dotcom-software