Efficient Decimal Handling In JavaScript – TinyFloat.js

Category: Javascript , Recommended | February 15, 2024
Views Total:10 views
Official Page:Go to website
Last Update:February 15, 2024


Efficient Decimal Handling In JavaScript – TinyFloat.js


Dealing with decimals can often lead to unexpected challenges in JavaScript development.

The standard IEEE 754 floats come with their well-known quirks, like the baffling result of adding 0.1 and 0.2.

Enter TinyFloat, a lightweight TypeScript library that solves decimal math problems in JavaScript.

It has no dependencies compared to heavier libraries like decimal.js.

For most use cases like working with money, the extra precision is unnecessary so TinyFloat is a great option.

How to use it:

1. Install and import the TinyFloat module.

$ npm install tinyfloat
import { TinyFloat } from "tinyfloat";

2. Create TinyFloat instances and use arithmetic methods like add, sub, mul, div, and mod.

// 0.3
new TinyFloat("0.1").add("0.2").toNumber();
// -0.1
new TinyFloat("0.1").sub("0.2").toNumber()
// 0.02
new TinyFloat("0.1").mul("0.2").toNumber()
// 0.5
new TinyFloat("0.1").div("0.2").toNumber()
// 0.1
new TinyFloat("0.1").mod("0.2").toNumber()

3. It also lets you specify precision and convert to string.

// 1.235
new TinyFloat("1.23456789", 3).toNumber();
// 0.3000000000000000
new TinyFloat("0.1").add("0.2").toString()
// 0.333333333333333333...
const ex = new TinyFloat("1").div("3");
// 0.333
// 0.33


v1.0.0 (02/15/2024)

  • Bugfix

You Might Be Interested In:

Leave a Reply