On 26/04/2023 11:29, Alexander Pravdin wrote:
As a user, I want to have native decimal scalar type support.
In general, I would absolutely love to have this.
1) Use a native numeric variable type compatible with other numeric
types without typecasts: 1 + 0.5 (int + decimal).
Although not shouted about much in the manual, GMP objects have
overloads for arithmetic operators, e.g.
$var = gmp_init('50000000000000000000000000000000000000000000000');
var_dump(1 + $var);
Results in:
object(GMP)#2 (1) { ["num"]=> string(47)
"50000000000000000000000000000000000000000000001" }
I'm not clear whether php-decimal has the same overloads, but it
certainly *can*, without any other changes to the language.
2) Do not use BCMath that uses strings.
You have to load the value somehow; bcmath accepts strings directly, so
parses the values each time, which isn't very efficient; but php-decimal
uses strings to construct objects, as does GMP. I guess the other option
for a decimal would be a pair of integers (whole part and fractional part).
The only improvement over that would be a special syntax that did more
of the processing at compile-time, but I don't know how much difference
that would actually make.
In PHP8, passing float values
to BCMath may lead to issues due to type mismatch which is a
mind-blowing counter-intuitive issue.
Far from counter-intuitive, that's an essential feature of any decimal
implementation - as soon as the value is in a floating point variable,
it's *already too late* to make it a fixed-precision decimal.
The php-decimal homepage at http://php-decimal.io/#basic-usage makes
this very clear:
> Special float values are also supported (NAN, INF and -INF), but
float is otherwise not a valid argument in order to avoid accidentially
using a float. If you absolutely must use a float to construct a decimal
you can cast it to a string first, but doing so if affected by the
precision INI setting.
>
> Projects using this extension should avoid float entirely, wherever
possible. An example workflow is to store values as DECIMAL in the
database, query them as string, parse to Decimal, perform calculations,
and finally prepare for the database using toFixed.
4) Available on any PHP distribution by default, including commercial
hostings where I can not install additional extensions.
This is largely out of PHP's control, unless we make it *impossible* to
disable the functionality, which isn't something that happens very
often. "Bundled" extensions have a higher chance of being installed than
PECL ones, but the "default" list is pretty much up to whoever
configures PHP (the Linux distro, hosting company, etc).
That's assuming we go down the "object with efficient constructor and
operator overloading" route. If we made deeper changes to make it scalar
(which would be A LOT of work), it would be there for everyone.
Regards,
--
Rowan Tommins
[IMSoP]
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php