27 lines
835 B
TypeScript
27 lines
835 B
TypeScript
import { Injectable } from '@angular/core';
|
|
import { evaluate, round } from 'mathjs';
|
|
|
|
@Injectable({
|
|
providedIn: 'root',
|
|
})
|
|
export class MathService {
|
|
parseAmount(amount: string = '', rounding: number = 2): number {
|
|
const cleaned = `${amount}`.replace(new RegExp('(₹[s]*)|(,)|(s)', 'g'), '');
|
|
if (cleaned === '') {
|
|
return 0;
|
|
}
|
|
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);
|
|
}
|
|
}
|
|
}
|