Search code examples
phpfloating-pointprecisionnumber-formattingphp-8.1

Is There any way to use min of 16 digit after decimal point to perform arithmetic operation in PHP


My actual value is: 0.990641327804487 but while doing php arithmetic operation it convert this number into 0.99064132780449

I have tried number_format function, if i convert it into number_format it returns me an string. But need it as number.


Solution

  • PHP, like just about any other modern general-purpose programming language, doesn't use any number of decimal digits to process mathematical operations. Instead, it uses a binary floating point representation, which has variable precision in a fixed number of bits. Specifically, PHP uses "double precision" 64-bit IEEE standard floating point; that is the format you are reaching the limits of.

    To use a higher precision, you need to use a specialist library for doing arbitrary precision arithmetic. These will generally be a lot slower than the built-in floating point operations - floating point operations are built into modern CPUs, arbitrary precision maths is not. One such library which is bundled with PHP is bcmath.

    It's important to understand that these libraries can't bring back accuracy that's not there in an existing floating point number. You generally have to provide your input values as strings, to be converted into some custom format internally.