Skip to content

Quick Start

Installation

bash
npm install smart-unit

If High Precision Calculation is Needed

bash
npm install smart-unit decimal.js

Basic Usage

1. Creating Instances

ts
import SmartUnit from 'smart-unit'

// Use baseDigit to auto-generate ratios
const size = new SmartUnit(['B', 'KB', 'MB', 'GB'], { 
  baseDigit: 1024 
})

// Manually specify the ratio for each unit
const length = new SmartUnit(['mm', 10, 'cm', 100, 'm', 1000, 'km'])

2. Formatting Output

ts
size.format(1536)              // => "1.5KB"
size.format(1024 * 1024 * 100) // => "100MB"

3. Parsing Strings

ts
size.parse('1.5KB')  // => 1536
size.parse('2MB')    // => 2097152

Internationalization Support

Reverse parsing supports internationalized strings. After using internationalization, only strings in the specific language can be correctly parsed. Original units will no longer be recognized.

Note

Reverse parsing only supports strings generated by or compatible with the format method. If you use getUnit to get the unit and then manually format it, it's usually not supported.

Core Concepts

Unit Array

SmartUnit accepts two formats of unit arrays:

Format 1: Using baseDigit (Recommended)

ts
new SmartUnit(['B', 'KB', 'MB', 'GB'], { baseDigit: 1024 })

Format 2: Manually Specifying Ratios

ts
new SmartUnit(['mm', 10, 'cm', 100, 'm', 1000, 'km'])

Configuration Options

ts
new SmartUnit(units, {
  baseDigit: 1024,        // Auto-generate ratios
  threshold: 1,           // Threshold for unit switching
  fractionDigits: 2,      // Number of decimal places
  separator: ' ',         // Separator, only used in `formatChain` method
  decimalOptions: {},     // Decimal.js configuration (only valid in high-precision mode)
})

Try It Online

Edit in CodeSandbox

Visit CodeSandbox Example to try it online.

Next Steps

Released under the MIT License.