Using Half-Round-Even rounding in the bill amounts as this is what python round uses.

When the bill amounts were Odd number + .5, payment could not be received as javascript rounded it up, but python rounded it down.
We are now using the python rounding (Half Round Even / Banker's Rounding) in the bill service.
This commit is contained in:
2021-03-20 08:05:50 +05:30
parent 0775d12271
commit 669821a643
2 changed files with 21 additions and 8 deletions

View File

@ -5,7 +5,6 @@ import { evaluate, round } from 'mathjs';
providedIn: 'root',
})
export class MathService {
// eslint-disable-next-line class-methods-use-this
parseAmount(amount: string = '', rounding: number = 2): number {
const cleaned = `${amount}`.replace(new RegExp('(₹[s]*)|(,)|(s)', 'g'), '');
if (cleaned === '') {
@ -13,4 +12,15 @@ export class MathService {
}
return round(evaluate(cleaned), rounding);
}
halfRoundEven(x: number, n = 0): number {
const fraction = Math.round(x * Math.pow(10, n + 8)) % Math.pow(10, 8);
if (fraction > 50000000 - 1 && fraction < 50000000 + 1) {
// To compensate for floating point rounding errors
const floor = Math.floor(x * Math.pow(10, n));
return floor % 2 === 0 ? floor / Math.pow(10, n) : (floor + 1) / Math.pow(10, n);
} else {
return round(x, n);
}
}
}