Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
matronator opened this issue May 31, 2024 · 2 comments

Comments

@matronator
Copy link

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
Copy link
Member

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:

  • BigRational::dividedBy() only needs a divisor
  • BigInteger::dividedBy() needs a divisor and a rounding mode
  • BigDecimal::dividedBy() needs a divisor, a scale and a rounding mode

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).

@BenMorel
Copy link
Member

Closing this as not planned for now. Please feel free to comment if you think this should be reopened!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants