Last active
November 16, 2021 06:12
-
-
Save ericdowell/b1bf9f681820b0911d4642588e268e69 to your computer and use it in GitHub Desktop.
Correct Floating Point Math
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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