core 1.0.2
Install from the command line:
Learn more about npm packages
$ npm install @float-toolkit/core@1.0.2
Install via package.json:
"@float-toolkit/core": "1.0.2"
About this version
Float Toolkit is a lightweight, dependency-less Node.js package that allows you to work with floats (floating-point numbers, or numbers with decimals).
You can round floats down to any number of digits, and perform accurate math operations (addition, subtraction, multiplication and division) with them.
To add Float Toolkit to your Node.js project, run this command:
npm install @float-toolkit/core
The package export is a class
called FloatToolkit
. Once you import it, you can create multiple FloatToolkit
instances.
NOTE: Version 1.0.2
and later only support ESM imports. Earlier versions are deprecated because of CommonJS imports conflicting with TypeScript type declarations.
import FloatToolkit from "@float-toolkit/core";
const ft = new FloatToolkit();
You are now ready to use Float Toolkit.
console.log(0.1 + 0.2); // 0.30000000000000004
console.log(ft.round(0.1 + 0.2)); // 0.3
console.log(ft.add([0.1, 0.2])); // 0.3
Float Toolkit is written in TypeScript. As such, the package is fully compatible with TypeScript projects. All of the type aliases and interfaces you might need can be imported into your project.
import FloatToolkit, { FloatToolkitOptions } from "@float-toolkit/core";
const createFT = (options: FloatToolkitOptions) => new FloatToolkit(5, options);
In JavaScript, certain math operations with floats can return values with slight imperfections. This can result in unexpected behavior.
const result = 0.1 + 0.2; // 0.30000000000000004
console.log(result === 0.3); // false
Often, developers address this issue by accepting a certain range of floats that includes the exact one they are looking for, like so:
console.log(result >= 0.299 && result <= 0.301); // true
This is not ideal, since this condition also becomes true if another value falls in the same range, even if it's not the expected value. For example, a value of 0.3005
would also pass this condition.
Another options is to round the number using Vanilla JS functions.
const roundedResult = Number(result.toFixed(1)); // 0.3
console.log(roundedResult === 0.3); // true
This alternative fixes the main problem the previous solution has, but it also increases the amount of boilerplate code, since it requires you to add Number(variable.toFixed(precision))
for every single number.
The Float Toolkit syntax is much cleaner and more concise.
const result = ft.add([0.1, 0.2]); // 0.3
console.log(result === 0.3); // true
Before creating an issue, please consider the following:
- Refer to the documentation to make sure the error is actually a bug and not a mistake of your own.
- Make sure the issue hasn't already been reported or suggested.
- After following these steps, you can read the contribution guidelines and follow the steps to submit a PR.