Skip to content

Instantly share code, notes, and snippets.

@ericdowell
Last active November 16, 2021 06:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericdowell/b1bf9f681820b0911d4642588e268e69 to your computer and use it in GitHub Desktop.
Save ericdowell/b1bf9f681820b0911d4642588e268e69 to your computer and use it in GitHub Desktop.
Correct Floating Point Math
import { format } from 'util';
export const addDecimals = (...decimals: number[]): number => {
let total = 0;
for (const value of decimals) {
const fixedValue =
typeof value.toFixed === 'function' ? Number(value.toFixed(2)) : value;
const addition = (total * 100 + fixedValue * 100) / 100;
if (Number.isNaN(addition)) {
throw new Error(
format(
'Adding together total: %s and value: %s (typeof %s) resulted in not a number.',
total,
fixedValue,
typeof fixedValue,
),
);
}
total = Number(addition.toFixed(2));
}
return total;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment