count significant digits in PHP

85 Views Asked by At

i am writing a class that does simple bcmath operations on numbers. tho i need to set the scale automatically throughout this so i need a way to determine how many significant digits a number has.

for small and simple numbers converting it to string and a simple explode and strlen would do the job but bigger numbers are converted into scientific form therefor i cant think of anything.

$test = 100000000000000.00000000000000001;

var_dump($test);
var_dump($test.'');

enter image description here

1

There are 1 best solutions below

2
On

You're defining your input data as float, which basically defeats the purpose of having an arbitrary precision library because you've already lost precision before data has the chance of reaching BC Math:

$test = 100000000000000.00000000000000001;

You need to handle input as string:

$input = '100000000000000.00000000000000001';
[$integerPart, $decimalPart] = explode('.', $input);
$result = bcadd($input, '9', strlen($decimalPart));

var_dump($input, $result);