Hacker News new | past | comments | ask | show | jobs | submit login

In PHP, as in other languages, numeric types that aren't ints should be avoided as much as possible. If you don't know why, smarter people can explain it, but the basics are that the binary nature of computers (every value is 0, 1, or a combination thereof) doesn't really work for reflecting decimal values without some level of fakery.

When working with things like money amounts, lengths, etc, store values as ints of the smallest denominator you support. For example, store $1.23 as 123 cents, or 4.567 meters as 4567 tenths of a centimeter. If you want to still allow the user to be able to, for example, enter a price as 1.23, multiply by 100 on input (like `$priceInCents = round($_POST['price'] * 100);`) and divide by 100 when displaying the value(`number_format($priceInCents / 100, 2)`), but keep it as an int all the way in between.

In terms of PHP, this also makes empty() a lot more predictable, because once a value is cast as int, the only time empty() will return true is if it is zero - or you could explicitly code `$priceInCents === 0` and have the exact same result.




Consider applying for YC's Fall 2025 batch! Applications are open till Aug 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: