Why I wouldn't use float for currency?

30/08/2020 21:34 BST

Okay like many people so you might have seen the price tag of something £9.50 and because of that you would have thought that float is great for currency, but what if I told you that float is the worst data type to use for dealing with currency, the reason why it’s not suitable for currency because float can be unpredictable and volatile, say for example you type in 9.50, save it to the database, then fetch it from the database and you might end up getting something like 9.49999999 and that can lead to miscalculation and can be problematic.

The thing with float is that it’s can’t accurately represent the base 10 multiples that we use for money, the more ideal datatype for money would be an integer for example just save £9.50 as 950 in integer and format it as you are outputting it.

Unfortunately using float for currency is a very common mistake in the world of computer science. Also, be mindful about JavaScript it’s the only language I know to my knowledge that does not support integer just float, if you can avoid using backend JavaScript (or Node.Js) than you should, otherwise I would advise using TypeScript, even with that I’m not sure that it would actually the avoid the float issue.

Don’t get me wrong float is suitable for many things, like coordination (GPS and Vectors), but currency is not one of them.

| |

Privacy Policy | CV