Decimal rounding following abnt 5891 [closed]

closed . This question needs to be more objective and is not currently accepting answers.

want to improve this question? update the question to focus on just one problem when edit it .

Closed 2 years ago .

improve this question

Good Morning!

Question:

Is there any library, or function, that makes rounding according to the abnt NBR standard 5891?

Problem:

I have to implement in JavaScript a rounding rule following the standard ABNT NBR 5891:2014. I tried to use only the existing functions like Math.round, Math.trunk, Math.floor, Math.ceil, though none gave 100%, the one that came closest was Math.round.

The rule and the following:

  1. when the digit immediately following the last digit to be retained is less than 5, the last digit a be preserved will remain unchanged.
  2. where the digit immediately following the last digit to be retained is greater than 5, or, if 5, is followed by at least one digit other than zero, the last digit to be retained shall be increased by one unit.
  3. when the digit immediately following the last digit to be preserved is 5 followed by zeros, The digit to be preserved should be rounded to the nearest even digit. Consequently, the last digit to be removed, if it is odd, will increase one unit.
  4. when the digit immediately following the last to be preserved is 5 followed by zeros, if it is even the Digit to be preserved, it remains unchanged.

In the examples below we are applying the ABNT rule rounding to 2 decimal places. Note that 0 is considered even.

EX: [0.342, 0.346, 0.3452, 0.3450, 0.332, 0.336, 0.3352, 0.3350, 0.3050, 0.3150]

By the rule: [0.34, 0.35, 0.35, 0.34, 0.33, 0.34, 0.34, 0.34, 0.3, 0.32]

Math.round [0.34, 0.35, 0.35, 0.35, 0.33, 0.34, 0.34, 0.34, 0.31, 0.32]

Math.trunc [0.34, 0.34, 0.34, 0.34, 0.33, 0.33, 0.33, 0.33, 0.3, 0.31]

Math.floor [0.34, 0.34, 0.34, 0.34, 0.33, 0.33, 0.33, 0.33, 0.3, 0.31]

Math.ceil [0.35, 0.35, 0.35, 0.35, 0.34, 0.34, 0.34, 0.34, 0.31, 0.32]

What would be the best way to adapt these rules in JavaScript?

Author: Pyetro, 2018-11-29