Skip to content

Instantly share code, notes, and snippets.

@juliarose
Created April 5, 2024 19:47
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 juliarose/f2b5aaa2c71b90d536668e0143d16936 to your computer and use it in GitHub Desktop.
Save juliarose/f2b5aaa2c71b90d536668e0143d16936 to your computer and use it in GitHub Desktop.
Demonstrates one method of adding floating-point refined metal values in JavaScript.
// Source:
// https://github.com/Nicklason/node-tf2-currencies
const ONE_REF_SCRAP = 9;
// Convert a number in refined to scrap
function toScrap(refined) {
return Math.round(refined * ONE_REF_SCRAP);
}
// Convert a number in scrap to refined
function toRefined(scrap) {
if (scrap === 0) {
// If the number is 0, no need to do any calculations
return 0;
}
// Convert back into a number in refined
scrap = scrap / ONE_REF_SCRAP;
// Truncate to 2 decimal places
return truncate(scrap, 2);
}
// Truncate a number to a certain number of decimal places
function truncate(number, places) {
const pow = Math.pow(10, places);
number = Math.abs(number * pow);
const isPositive = number >= 0;
// If we add 0.001 and it is greater than the number rounded up,
// then we need to round up to fix floating point error
const round = number + 0.001 > Math.ceil(number) ? Math.round : Math.floor;
number = round(number);
if (!isPositive) {
number *= -1;
}
return number / pow;
}
function addRefineds(...currencies) {
// Convert all currencies to scrap
const scrap = currencies.reduce((total, currency) => total + toScrap(currency), 0);
// Now back to refined
return toRefined(scrap);
}
// Add 1.33 ref and 0.11 ref together
const metal = addRefineds(1.33, 0.11);
console.log(metal); // 1.44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment