Socket
Socket
Sign inDemoInstall

decifloat

Package Overview
Dependencies
0
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    decifloat

Format floats as decimals as accurately as possible.


Version published
Weekly downloads
2
increased by100%
Maintainers
1
Install size
18.3 kB
Created
Weekly downloads
 

Readme

Source

decifloat

Build Status Coverage Status npm version

Format floats as decimals with expected rounding

This module formats floats to a given number of decimals with expected rounding, fixing some surprises with native Javascript method toFixed. It seeks to do this with minimal overhead.

Installation

npm install --save decifloat

Usage

decifloat.toFixed(num, minDecimals, maxDecimals, roundingFunc = Math.round)

Formats num to at least minDecimals and at most maxDecimals decimal digits after the decimal point.

import {toFixed} from 'decifloat';
console.log(toFixed(1.005, 0, 2));    // Outputs 1.01
console.log(toFixed(1.005, 0, 5));    // Outputs 1.005
console.log(toFixed(1.005, 5, 5));    // Outputs 1.00500
console.log(toFixed(1.005, 0, 1));    // Outputs 1

Explanation

Floats in Javascript (as in most modern languages) are represented using powers of 2, which means that most decimal fractions are not represented precisely. For example, 1.005 is not representable precisely in Javascript, and is represented by a slightly smaller number.

The native methods of Number such as toString() and toExponential() do a good job of formatting this slightly smaller number back as "1.005" for output.

However, because Javascript's 1.005 is actually a slightly smaller than the mathematical 1.005, rounding to two decimal digits, as done by (1.005).toFixed(2), produces "1.00", which looks wrong. For the same reason, 1.005 * 100 produces 100.49999999999999.

This module solves this issue by scaling "1.005" to "100.5" as a string before rounding. Because it doesn't lose precision in scaling by powers of 10, decifloat.toFixed(1.005, 2, 2) can correctly produce "1.01".

Beyond that, it aims to be fast. In many cases (at least on node 10) it's actually faster than the native toFixed() method.

Keywords

FAQs

Last updated on 07 Jan 2019

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc