Skip to content

Instantly share code, notes, and snippets.

@Andrei15193
Last active January 17, 2023 17:06
Show Gist options
  • Save Andrei15193/cf5cd871e78d14c4de402c5f62e81d7f to your computer and use it in GitHub Desktop.
Save Andrei15193/cf5cd871e78d14c4de402c5f62e81d7f to your computer and use it in GitHub Desktop.
Test JavaScript Rounding
const maximumNumberOfDecimals = 5;
const targetDecimals = 2;
const roundingAdjustment = 3;
// The more maximum number of decimals, the higher this needs to go for accurate results
// It looks like targetDecimals + roundingAdjustment = maximumNumberOfDecimals for fully accurate results
var results = [];
for (
let value = 1 / Math.pow(10, maximumNumberOfDecimals);
value <= 100;
value = (Math.round(value * Math.pow(10, maximumNumberOfDecimals)) + 1) / Math.pow(10, maximumNumberOfDecimals)
) {
if (value.toString().length > "100".length + ".".length + maximumNumberOfDecimals)
throw `Invalid step, ${value}`
results.push({
roundedValue: // round(value, targetDecimals, maximumNumberOfDecimals)
Math.round(
Math.round(
value * Math.pow(10, targetDecimals + roundingAdjustment)
) / Math.pow(10, roundingAdjustment)
) / Math.pow(10, targetDecimals),
initialValue: value
});
}
results.forEach(
(result, resultIndex) => {
if (resultIndex > 1
&& results[resultIndex - 1].roundedValue !== result.roundedValue) {
console.log(result, results[resultIndex - 1]);
}
}
);
// A relatively goood round function which can be used to get much more accurate
// results by specifying a value for `maximumNumberOfDecimalsForValue`.
function round(value, decimals, maximumNumberOfDecimalsForValue) {
if (typeof maximumNumberOfDecimalsForValue !== "number" || maximumNumberOfDecimalsForValue < decimals)
maximumNumberOfDecimalsForValue = decimals + 1;
return (
Math.round(
Math.round(
value * Math.pow(10, maximumNumberOfDecimalsForValue)
) / Math.pow(10, maximumNumberOfDecimalsForValue - decimals)
) / Math.pow(10, decimals);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment