Excel’s Round Function to JavaScript does not providing consistent results with compared to Excel

  • While translating the ROUND function from Excel to JavaScript, it’s noted that the differences in how each language handles floating-point arithmetic. In JavaScript, the .toFixed() method is not giving the same result as Excel due to the way JavaScript handles binary floating-point numbers.

  • .toFixed() method converts a number into a string, rounding to a specified number of decimal places, but it can be affected by the floating-point representation of numbers in JavaScript. For instance, the number 179.725 may be represented internally as slightly less than the actual value, resulting in toFixed(2) returning 179.72 instead of 179.73.

  • So that I have used to calculate the rounding result by adding 0.001 based on the last position of the provided number and it works properly as same as Excel for me. But the case is when the provided number has a value of 0.499, while rounding it adds 0.001 to it and results in a wrong value as compared to the Excel.

numValue = 0.3049945849;
decimalValue = 2;
sign = numValue >= 0 ? 1 : -1;
roundValue = (Math.round((numValue * Math.pow(10, decimalValue)) + (sign * 0.001)) / Math.pow(10, decimalValue)).toFixed(decimalValue);

I need a way to replicated the ROUND formula used is Excel in JavaScript