79436804

Date: 2025-02-13 15:12:10
Score: 0.5
Natty:
Report link

I have this solution for invoice application, it allow to round positive number (0.005 ==> 0.01) and négative number for credit (-0.005 ==> 0.01)

round(num: number, fractionDigits: number = 2): number {
        if (!isFinite(num)) return num; // Handle NaN, Infinity, and -Infinity

        const factor = Math.pow(10, fractionDigits);
        const result = Math.round((num + Math.sign(num) * Number.EPSILON) * factor) / factor;

        return result === 0 ? 0 : result; // Ensure `-0` becomes `0`
    }

I think something like this could be the solution at the probleme for positive number (0.005=>0.01) and négative number (-0.005 ==> 0):

round(num: number, fractionDigits: number = 2): number {
if (!isFinite(num)) return num; // Handle NaN, Infinity, and -Infinity
if (isNaN(num)) return NaN;

const factor = Math.pow(10, fractionDigits);
return result === 0 ? 0 : Math.round(num * factor) / factor;

}

Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Unregistered user (0.5):
  • Low reputation (1):
Posted by: MatDev