numberformatterwithcommas
v1.0.2
Published
A simple JavaScript function to format numbers with commas as thousands separators.
Maintainers
Readme
Number Formatter JS
A lightweight, pure JavaScript function to format numbers with commas as thousands separators. It safely handles invalid or non-numeric inputs by returning an empty string.
Installation
You can install the package using npm:
npm install numberformatterwithcommasUsage
1. Import the function
You can import the function using require (CommonJS) or import (ES Modules).
CommonJS (Node.js):
const numberWithCommas = require('numberformatterwithcommas');ES Modules (Modern JS):
import numberWithCommas from 'numberformatterwithcommas';2. Basic Formatting
const formattedAmount = numberWithCommas(1234567.89);
console.log(formattedAmount); // Output: "1,234,567.89"API
numberWithCommas(amount)
Parameter:
| Parameter | Type | Description |
|-----------|------|-------------|
| amount | number | string | The number to format |
Returns:
| Type | Description |
|------|-------------|
| string | The formatted number string, or an empty string ("") if the input is invalid (NaN, undefined, null, "", or the string "NaN"). |
Examples
| Input | Code | Output | Notes |
|-------|------|--------|-------|
| 1000 | numberWithCommas(1000) | "1,000" | Basic thousands separation. |
| 1234567.89 | numberWithCommas(1234567.89) | "1,234,567.89" | Handles decimals without affecting them. |
| "987654321" | numberWithCommas("987654321") | "987,654,321" | Works with number strings. |
| 0 | numberWithCommas(0) | "0" | Zero returns "0". |
| NaN | numberWithCommas(NaN) | "" | Invalid input returns empty string. |
| "" | numberWithCommas("") | "" | Empty string input returns empty string. |
| undefined | numberWithCommas(undefined) | "" | Undefined input returns empty string. |
License
ISC
Author
Zarrar Hussain Abid
