brick / math

Arbitrary-precision arithmetic library for PHP
MIT License
1.78k stars 75 forks source link

Add some generic number type when you don't know if the result will be `int` or `decimal` #80

Open matronator opened 1 month ago

matronator commented 1 month ago

As far as I know, the bc library (and gmp too I think) works on arbitrary precision numbers and doesn't discriminate between int or float/decimal. I am re-writing a TypeScript library to PHP and now need to use some BigNumber's math, but am not sure whether the calculations should be done on Integers or Decimals.

It would be great if there was some generic number type that would automatically convert to BigInt if there's no decimals after the calculation or BigDecimal otherwise.

BenMorel commented 1 month ago

Hi, this could have been BigNumber, which already knows how to handle comparison between types, and cross-type additions (see BigNumber::sum().

That being said, plus(), minus() etc. are already defined on subclasses, and they return an instance of the subclass. We cannot move the implementation to BigNumber, and make each operation return a potentially different type than the type you call the method on, without drastically changing the behaviour of the library (for the worse, IMO).

So this would need to be a new class indeed. But it comes with its own challenges: only addition / subtraction / multiplication could be implemented on this class, as the signature of dividedBy() in each number class is different:

I'm wondering, if you're re-writing a TS library to PHP, are you dealing with number types? Or with arbitrary precision? In the former case, the equivalent would just be using float in PHP. AFAIK, Both PHP's float and JS' number are IEEE 754 double-precision numbers, so you should observe the same behaviour (and the same gotchas, obviously).