1
Good morning!
Question:
Is there a library, or function, that makes rounding according to ABNT NBR 5891?
Problem:
I have to implement in Javascript a rounding rule following the standard ABNT NBR 5891:2014. I tried to use only existing functions like Math.round, Math.trunc, Math.floor, Math.Ceil, but none gave 100%, the one that got closer was Math.round.
The rule and the following:
- Where the digit immediately following the last digit to be preserved is less than 5, the last digit to be preserved shall remain unchanged.
- Where the digit immediately following the last digit to be preserved is greater than 5, or where 5 is followed by at least one digit other than zero, the last digit to be preserved shall be increased by one.
- When the digit immediately following the last digit to be preserved is 5 followed by zeros, the digit to be preserved shall be rounded off to the nearest even digit. Therefore, the last digit to be removed, if it is odd, will increase one unit.
- When the digit immediately following the last to be conserved is 5 followed by zeros, if it matches the digit to be conserved, it shall remain 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]
For 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?
First of all, mathematically speaking, 0 is an even number. Second, I suggest taking a look at this link to see the possibility of having rounding assertiveness: https://ridiculousfish.com/blog/posts/JavaScript-Rounding.html
– Angelo Simonato
In fact all this is wrong (and almost everyone does it wrong), the right is this: https://answall.com/q/11018/101 round on top of a number that has inaccuracies will always potentially give wrong results.
– Maniero
It would not be feasible to make a regex to round the way he wants?
– Máttheus Spoo
Hello, I performed this procedure for PHP, take a look maybe help you. I haven’t had time to refactor yet, but it has met the test requirements. https://github.com/fhferreira/round
– Flávio H. Ferreira