Skip to content
Advertisement

How to multiply small floats with unkown number of decimal places in PHP withouth getting zero because of scientific notation?

I’m trying to multiply some small numbers in PHP, but bcmul is returning zero because the float value is being turned into scientific notation.

I tried using sprintf('%.32f',$value) on the small float values, but since the number of decimal places is unknown, it gets the wrong rounding, and then it’ll cause rounding errors when multiplying.

Also, I can’t use strpos('e',$value) to find out if it’s scientific notation number, because it doesn’t finds it even if I cast it as a string with (string)$value

Here’s some example code:

JavaScript

Advertisement

Answer

Okay, I found a way to solve it, so, here’s how to multiply very small floating point numbers without needing to set an explicit scale for the numbers:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement