If dealing with money in a float is bad, then why does money_format() do it?

不羁的心 提交于 2019-11-28 23:09:49
dan04

Unless I'm dealing with fractional cents or trillions of dollars (and I'm dealing with neither), should I be concerned at all about displaying and storing (but never doing math on) currency that's been cast to a float? Will I ever come close to the area of having floating point inaccuracies change my figures?

For pure rounding/display purposes, you're safe as long as the absolute floating-point representation error is less than $0.005 (so that rounding to the nearest cent is correct).

With IEEE 754 single-precision, you're safe up to $131,072.00. ($131,072.01 is represented as 131072.015625, which incorrectly rounds up.)

Double precision (which PHP's float uses) doesn't fail until $70,368,744,177,664.01 (which also has .015625 for the cents). You have nothing to worry about.

If the answer to #1 is that I should indeed be concerned, then why is money_format() built this way?

What type should it take? PHP doesn't have a built-in decimal type. Nor do many other languages.

This is discussed in “Why are floating-point values so prolific?”

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!