0

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

Álvaro González
  • 142,137
  • 41
  • 261
  • 360

1 Answers1

3

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);
Álvaro González
  • 142,137
  • 41
  • 261
  • 360
  • well yes but the problem is that i *have* a float, from json, file or db. i think best way would be to parse the scientific form back to string. – محمدرضا خدامی Nov 29 '22 at 12:07
  • That makes the problem slightly different from what the question states. If you are using native JSON decoding, there's an opt-in feature for big integers, but I'm not aware of anything similar for floats (please see [demo](https://3v4l.org/YRFhc#v8.1.13)). You'll have to write your own JSON parser or find a third-party one that suits your needs. – Álvaro González Nov 29 '22 at 12:14