What the actual fuck.

PHP, why can't money_format() round properly? round() and number_format() works fine, why is money_format() doing it wrong half the time?

If you have a number with 3 digits after the dot (e.g. 0.005) and the last digit is 5; then money_format will fail to round up that number when rounding to two digits - but only half the time!

That is, half of the numbers between 0 and 1 that are on the form 0.xx5 get rounded down, and the other half gets rounded up. I counted.

Assuming that money_format() is a standard function, I think that in conventional #finance it's better to round down than to round up.

@bthall @zatnosk in conventional finance, you have to choose rounding rules that eliminate the worst types of bias. these are usually more complicated than the "round 0.5 up" that we learned as kids

This is so interesting! Thank you for sharing this. How do you know so much about it? :)

@bthall @zatnosk IEEE-754 (the floating point standard) is a masterpiece, full of tiny compromises about a few dozen obscure corner cases that come up when you start running a lot of numbers through computers. I made an implementation once at uni. it's an interesting standard to read through

one important takeaway is that it's not a suitable format for dealing with money. most languages will have a dedicated decimal or money format for that

@io @bthall ... which is what you'd expect a locale dependent function called "money_format" to represent, right? :P

@zatnosk @bthall yeah, any stdlib function with money in the name ought to work with decimals, not floats. there are too many floating point pitfalls: binary rounding causing numbers not to equal each other is the biggest imo

Sign in to participate in the conversation

Toots from Richmond, VA and around the world. Stick around for good vibes.