Float Toolkit

Float Toolkit

NPM latest version NPM downloads Tests status Code coverage with Codecov Contributor Covenant Code of Conduct

Float Toolkit is a lightweight, dependency-less NPM 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.

Features

  • Accurate math operations
  • Round floats to any number of digits
  • No dependencies
  • TypeScript type declarations
  • Compatible with browsers and Node.js
  • > 95% code coverage

Get started

Installation

To add Float Toolkit to your project, run this command:

npm install @float-toolkit/core

Usage

The package export is a class called FloatToolkit. Once you import it, you can create multiple FloatToolkit instances.

import FloatToolkit from "@float-toolkit/core";
const ft = new FloatToolkit();

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

TypeScript

Float Toolkit is written in TypeScript. As such, you will have full type checking in your TypeScript projects. The type definitions used by the package are exported on their own or through the FloatToolkit namespace.

import FloatToolkit from "@float-toolkit/core";

const createFT = (options: FloatToolkit.Options) => new FloatToolkit(5, options);

Why use Float Toolkit?

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

Support

Need help using Float Toolkit? Don't hesitate to reach out on GitHub Discussions!

Links

Child packages

Contributing

Before creating an issue, please consider the following:

Generated using TypeDoc