From 8300829761ebcd43adba61d4b55d86de95eaa1f0 Mon Sep 17 00:00:00 2001 From: superbuggy Date: Wed, 23 Oct 2024 11:30:18 -0400 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20Fix=20rouding=20more=20errors?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cvss40.js | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/cvss40.js b/cvss40.js index c6d8c1f..2e026cc 100644 --- a/cvss40.js +++ b/cvss40.js @@ -23,18 +23,23 @@ */ function roundToDecimalPlaces(value, decimalPlaces = 1) { // Step 1: Shift the decimal point by multiplying with 10^decimalPlaces - const factor = Math.pow(10, decimalPlaces); + const BUFFER_SIZE = 5; + const factor = Math.pow(10, BUFFER_SIZE); + const reRoundFactor = Math.pow(10, decimalPlaces); // Step 2: Apply the ROUND_HALF_UP logic by rounding to the nearest integer // After shifting the decimal point - let shiftedValue = value * factor; - let roundedValue = Math.round(shiftedValue); + const shiftedValue = value * factor; + const roundedValue = Math.round(shiftedValue); // Step 3: Shift the decimal point back by dividing with the same factor - let result = roundedValue / factor; + const unshiftedValue = (roundedValue / factor); - // Step 4: Ensure the result has the correct number of decimal places - return parseFloat(result.toFixed(decimalPlaces)); + // Step 4: Re-round the value with an additional buffering step to precent floating point rounding errors in previous step + const reRoundedValue = Math.round(unshiftedValue * reRoundFactor) / reRoundFactor; + + // Step 5: Ensure the re-rounded has the correct number of decimal places + return parseFloat(reRoundedValue.toFixed(decimalPlaces)); } /**