-1

I'm new to math in PHP. I'm working on calculating cryptocurrencies that have up to 18 decimal places. What is the best way to calculate this precisely in PHP? Most answers on SO are for other coding languages and about rounding.

For example, when I do the below, I don't get 0.000000000000000001 as an answer.

        $a= 0.000000000000000002;
        $b= 0.000000000000000001;

        $balance = $a - $b;

What I get is -8.0E-20 which is not 0.000000000000000001 (i think).

Also, [from here][1], it says float has a max of 14 decimal places but then it used the word "roughly."

[1]: https://www.php.net/manual/en/language.types.float.php#:~:text=The%20size%20of%20a%20float,the%2064%20bit%20IEEE%20format).

mewiben39
  • 121
  • 9
  • "*For example, is the below correct?*" Correct in what sense? Does it meet your requirements? – esqew May 10 '22 at 02:16
  • @esqew meaning, I don't get the answer which supposed to be precisely 0.000000000000000001 – mewiben39 May 10 '22 at 02:24
  • 3
    If you want precision, eg: for units of currency, _do not use floats_. Store and calculate currency values as integers of base units, eg: $1 == 100 cents, 1BTC = 1,000,000 satoshis, etc. See: https://stackoverflow.com/questions/588004/is-floating-point-math-broken – Sammitch May 10 '22 at 02:57
  • Precision is for output only. Check php.ini for `precision=14` (where 14 is the default value). You can increase that and will then see more decimal places in the output. – Honk der Hase May 10 '22 at 06:52

1 Answers1

-1

To keep your precision when displaying, you must use a Float Data type, see the floatval() function for more help.

Up to 18 places is an arbitrary amount more than the supported size, which is 14 on most machines depending on memory?

As mentioned in the comments using defined base units would solve the problem, to expand on that to be a more generalized solution that is more scalable, applicable to more algorithms, is to create a new class to hold this data type, dynamic float (d_float) is what I would use, cc_value = new d_float(value: int, pof10: int); cc_value * pof10; Where crypto currency value is described by a integer value that contains each digit and a second integer that can be applied to return the correct decimal value. Different base amounts could simply be extensions of the d_float class and therefore have fixed pof10 values?