Skip to content

Instantly share code, notes, and snippets.

@brookjordan
Last active March 2, 2019 16:03
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 brookjordan/737293352eeb59394703f1b3395ae658 to your computer and use it in GitHub Desktop.
Save brookjordan/737293352eeb59394703f1b3395ae658 to your computer and use it in GitHub Desktop.
Functions that deal with numbers when accuracy is more important than speed
class Accounting {
static largestNumber = 10e9; // America's annual budget is ~4tn
static accuracy = (function() {
let accuracy = 1;
while (Accounting.largestNumber * accuracy < Number.MAX_SAFE_INTEGER) {
accuracy *= 10;
}
return accuracy;
}()); // to change to #accuracy when support rises
static sum(...args) {
let arg = args.pop();
let currentSum = arg * Accounting.accuracy;
while(!isNaN(arg = args.pop())) {
currentSum += arg * Accounting.accuracy;
}
return currentSum / Accounting.accuracy;
}
static subtract(...args) {
let arg = args.shift();
let currentSum = arg * Accounting.accuracy;
while(!isNaN(arg = args.shift())) {
currentSum -= arg * Accounting.accuracy;
}
return currentSum / Accounting.accuracy;
}
static multiply(...args) {
let arg = args.pop();
let currentSum = arg * Accounting.accuracy;
while(!isNaN(arg = args.pop())) {
currentSum *= arg;
}
return currentSum / Accounting.accuracy;
}
static divide(...args) {
let arg = args.shift();
let currentSum = arg * Accounting.accuracy;
while(!isNaN(arg = args.shift())) {
currentSum /= arg;
}
return currentSum / Accounting.accuracy;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment