1

I'm using the decimal.js to calculate with numbers and using the advantages by handling big numbers..

Now i came to the point where i want to round numbers to a specific multiplicator.

everything worked fine, until i found this issue;

new Decimal(750).toNearest(500,3).toNumber() //-> 500

this line will output 500. Is it simply a bug or did I made a fault in my code? And if its a fault i'm wondering why its happening only at this specific numbers showed below...

new Decimal(75).toNearest(50,2).toNumber() //-> 100
new Decimal(7500).toNearest(5000,4).toNumber() //-> 10'000

when u play a little bit with these statements at decimal.js API

only the 3 digit number could be round correctly:

new Decimal(300).toNearest(200,3).toNumber() //-> 200
new Decimal(450).toNearest(300,3).toNumber() //-> 300
new Decimal(600).toNearest(400,3).toNumber() //-> 400
msrd0
  • 7,816
  • 9
  • 47
  • 82
Synoon
  • 2,297
  • 4
  • 22
  • 37

1 Answers1

2

Please care of the second property in .toNearest-function: https://mikemcl.github.io/decimal.js/#modes

2: Rounds towards Infinity (up)
3: Rounds towards -Infinity (down)
4: Rounds towards nearest neighbour. If equidistant, rounds away from Zero.

So you have to think about what the expected result should be and choose the correct rounding method. The rounding method has nothing to do with the number of digits.

new Decimal(75).toNearest(50,2).toNumber() //-> 100
new Decimal(75).toNearest(50,3).toNumber() //-> 50
new Decimal(75).toNearest(50,4).toNumber() //-> 100
zuluk
  • 1,557
  • 8
  • 29
  • 49