Ethers.js: Add floor and ceiling to FixedNumber

Created on 7 Sep 2020  路  10Comments  路  Source: ethers-io/ethers.js

enhancement fixed

Most helpful comment

Oh! That is actually something I鈥檝e been meaning to add, but it hasn鈥檛 been a priority. But I can add it this week.

I plan to support a bunch of tie-breaking rounding algorithms:

  • round half up (this is what round currently does)
  • round up (ceiling)
  • round down (floor)
  • round toward zero
  • round away from zero
  • round to odd
  • round to even

For now I will add floor and ceiling. If there is any other rounding strategy you need though, let me know.

All 10 comments

An important reason why ethers has its own implementation of BigNumber is to be immutable.

So no in-place operations are available...

It makes things much simpler throughout the async nature of blockchain that capturing a reference is sufficient (also copying is fast; just store a reference) which requires all numbers remain immutable. Sorry. :s

Is there an equivalent workaround with existing methods?

Well, you can just re-assign to the original value. :)

// equivalent to value.idiv(divisor)
value = value.div(divisor);

Ah - okay sorry, I was not referring to inplace division, I was referring to integer division: https://mikemcl.github.io/bignumber.js/#divInt

Oh, I see. That makes more sense. :)

The BigNumber class will likely never support that, however, you can use the FixedNumber class to get something similar:

x = FixedNumber.from("5");
y = FixedNumber.from("0.7");

quotient = x.divUnsafe(y));
// "7.142857142857142857"

quotient.round()
// "7.0"

You can also specify the internal fixed format to use, which is by default fixed128x18 (i.e. 128 bits wide, representing 18 decimals).

Does that help?

bare with me - I am a math noob

Is is possible to have a way for specifying if division rounds up or down?

Oh! That is actually something I鈥檝e been meaning to add, but it hasn鈥檛 been a priority. But I can add it this week.

I plan to support a bunch of tie-breaking rounding algorithms:

  • round half up (this is what round currently does)
  • round up (ceiling)
  • round down (floor)
  • round toward zero
  • round away from zero
  • round to odd
  • round to even

For now I will add floor and ceiling. If there is any other rounding strategy you need though, let me know.

I've added a .floor and .ceiling method to BigNumber in 5.0.13. Try it out and let me know if it works for you.

Thanks! :)

This has been published, so I'm going to close it now. If you have any issues though, please re-open.

Thanks! :)

I've been trying to convert this function into using only ethers BigNumber - any tips?
image

Was this page helpful?
0 / 5 - 0 ratings