commafy-anything

Adds comma's to a number. A simple and small integration

Usage no npm install needed!

<script type="module">
  import commafyAnything from 'https://cdn.skypack.dev/commafy-anything';
</script>

README

Commafy anything 🍡

Total Downloads Latest Stable Version

npm i commafy-anything

Adds comma's to a number. A simple and small integration.

Motivation

U built this package because I needed to add comma's to numbers! And I wanted to build it myself. 😄

Meet the family

Usage

import { commafy } from 'commafy-anything'

commafy(1000) === '1,000'
commafy(10000) === '10,000'
commafy(100000) === '100,000'
commafy(1000000) === '1,000,000'
// etc.

Thousands

// default:
commafy(1000) === '1,000'

// thousands:
const options = {thousandsComma: false}
commafy(1000, options) === '1000'
commafy(10000, options) === '10,000'

Spaced decimals

// default:
commafy(1.0001) === '1.0001'
commafy(1.00001) === '1.00001'
commafy(1.000001) === '1.000001'
commafy(1.0000001) === '1.0000001'

// spaced decimals:
const options = {spacedDecimals: true}
commafy(1.0001, options) === '1.0001'
commafy(1.00001, options) === '1.000 01'
commafy(1.000001, options) === '1.000 001'
commafy(1.0000001, options) === '1.000 0001'

Strip decimals

// default:
commafy(1.0001) === '1.0001'

// strip decimals:
const options = {stripDecimals: true}
commafy(1.001, options) === '1'
commafy(1.999, options) === '1'

Source code

I'm using simple regular expressions. The source code is in TypeScript, but the essense of my source code looks something like this:

function commafy (num, {stripDecimals, spacedDecimals} = {}) {
  const str = num.toString().split('.')
  if (str[0].length >= 4) {
    str[0] = str[0].replace(/(\d)(?=(\d{3})+$)/g, '$1,')
  }
  if (stripDecimals) return str[0]
  if (spacedDecimals && str[1] && str[1].length >= 5) {
    str[1] = str[1].replace(/(\d{3})/g, '$1 ').trim()
  }
  return str.join('.')
}