UNPKG

format-num-util

Version:

A utility function to format numbers with currency, unit and millify support.

86 lines (58 loc) 2.18 kB
# format-num-util > A simple, zero-dependency utility to format numbers with optional currency, unit, and millified output. --- ## ✨ Features - Indian-style comma formatting (`12,34,567.89`) - Add currency symbol (₹, $, etc.) - Add unit (kg, km, etc.) - Millify large numbers (e.g., 1.2K, 3.5M) - Handles negative values and edge cases - No external dependencies --- ## 📦 Installation ```bash npm install format-num-util ``` --- ## 🚀 Usage ```js import formatNum from 'format-num-util'; // Example 1: Regular formatting console.log(formatNum({ num: 1234567.89, curr: '₹', unit: 'km' })); // Output: ₹12,34,567.89 km // Example 2: Millify large number console.log(formatNum({ num: 1234567.89, curr: '$', millify: true })); // Output: $1.2M // Example 3: Negative number console.log(formatNum({ num: -123.456, unit: 'kg' })); // Output: -123.46 kg ``` --- ## 🔍 Edge Case Handling ```js formatNum({ num: '' }); // "-" formatNum({ num: null }); // "-" formatNum({ num: 'abc' }); // "-" formatNum({ num: 999 }); // "999" formatNum({ num: 1200000, millify: true }); // "1.2M" ``` --- ## 📘 API Reference ### `formatNum({ num, curr, unit, millify })` | Param | Type | Required | Description | |-----------|--------------------|----------|--------------------------------------------| | `num` | `number \| string` | Yes | The number to format | | `curr` | `string` | No | Currency symbol to prefix (e.g. ₹, $) | | `unit` | `string` | No | Unit to append (e.g. kg, km) | | `millify` | `boolean` | No | Shorten large numbers like 1K, 1M (default: false) | --- ## 🧠 When to Use Use this utility for: - Dashboards - Financial summaries - Product pricing - Analytics charts - Anywhere numbers need to look clean and human-readable --- ## 📄 License MIT free for personal & commercial use.