# auto-unit

> ![npm](https://img.shields.io/npm/v/auto-unit) ![npm bundle size](https://img.shields.io/bundlephobia/minzip/auto-unit) 中文文档 | English

Latest version **3.0.5** (published 2025-05-14) · MIT license · 0 weekly downloads

> **Deprecated.** This package is deprecated.

## Install

```sh
npm install auto-unit
pnpm add auto-unit
yarn add auto-unit
bun add auto-unit
```

## Health

**Score 10/100 (F)** — status: deprecated.

Negative: deprecated.

## Facts

| | |
|---|---|
| Version | 3.0.5 |
| Published | 2025-05-14 |
| First published | 2023-11-22 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Dependencies | 1 |
| Unpacked size | 67.4 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 1 |
| Author | Flycran |
| Maintainers | cffhidol |
| Keywords | Automatically select the appropriate unit of measurement |

## Links

- npm: https://www.npmjs.com/package/auto-unit
- Repository: https://github.com/flycran/auto-unit
- Issues: https://github.com/flycran/auto-unit/issues
- npm.io page: https://npm.io/package/auto-unit

## Dependencies (1)

- [decimal.js](https://npm.io/package/decimal.js.md) ^10.5.0

## Recent versions

- 3.0.5 (latest) — 2025-05-14
- 3.0.4 — 2025-05-02
- 3.0.3 — 2025-05-02
- 3.0.2 — 2025-05-02
- 3.0.1 — 2025-05-02
- 3.0.0 — 2025-05-02
- 2.0.0 — 2025-05-01
- 1.0.2 — 2023-11-22
- 1.0.1 — 2023-11-22
- 1.0.0 — 2023-11-22
- 0.1.0 — 2023-11-22

## README

# AutoUnit

English documentation is translated by AI. If you have any questions about the content, please refer to the [Chinese document](./README.zh.md). Contributions to improve translations are welcome.

<div align="center">
<a href="./README.zh.md">中文文档</a>
|
<a href="./README.md">English</a>
</div>

`AutoUnit` is a utility class for automatic unit conversion, supporting custom unit systems, thresholds, and decimal place configurations.

- Automatically selects appropriate units to output formatted strings
- Reverse parses numeric values from unit-formatted strings
- Quickly build any unit system
- Supports high-precision calculations
- Supports calculations beyond JS safe number ranges

## Quick Links

- [Quick Start](#quick-start)
- [Best Practices](#best-practices)
- [API](#api)
- [Contributing](#contributing)

## Quick Start

- **Fixed-base Units**

```ts
import AutoUnit from 'auto-unit';

const autoUnit = new AutoUnit([ 'B', 'KB', 'MB', 'GB', 'TB', 'PB' ], {
  baseDigit: 1024,
})

console.log(autoUnit.format(1024 * 1024 * 100)) // 100MB
```

> The `baseDigit` parameter represents the conversion base between units. For example, 1024 means 1KB equals 1024 bytes.

- **Variable-base Units**

```ts
import AutoUnit from 'auto-unit';

const autoUnit = new AutoUnit([ 'mm', 10, 'cm', 100, 'm', 1e3, 'km' ])

console.log(autoUnit.format(1000)) // 1m
```

> You can customize conversion bases between units. For example, [ 'mm', 10, 'cm', 100, 'm', 1e3, 'km' ] means:
> 1 cm equals 10 mm, 1 m equals 100 cm, and 1 km equals 1000 m.

- **High Precision & Large Integers**

```ts
import AutoUnit from 'auto-unit';

const units = [ 'mm', 10, 'cm', 100, 'm', 1e3, 'km', 1e3, 'Mm', 1e3, 'Gm', 1e3, 'Tm' ]
const autoUnit = new AutoUnit(units, { highPrecision: true })

console.log(autoUnit.format(1e18)) // 1000Tm
```

> The `highPrecision` parameter enables high-precision mode using `decimal.js`. It supports `number`, `string`, `BigInt`, and `Decimal` inputs.

## Best Practices

- For most use cases requiring formatted unit strings, consider wrapping `format`:

```ts
import AutoUnit from 'auto-unit';

const autoUnit = new AutoUnit([ 'B', 'KB', 'MB', 'GB', 'TB', 'PB' ], {
  baseDigit: 1024,
})

export const formatFileSize = (num: number) => {
  return autoUnit.format(num)
}
```

- In modular projects (e.g., React/Vue), pre-initialize unit systems globally (e.g., in `utils/units.ts`) rather than recreating them per component.

## API

### **Constructor**

```ts
class AutoUnit {
  constructor(
          readonly units: (string | number)[],
          option: AutoUnitOptions<DS> = {},
  ) {}
}
```

- **Parameters**:
  - `units`: Unit array.
  - `option`: Configuration options.
    - `baseDigit?`: Base number for auto-generating unit conversions.
    - `threshold?`: Unit switch threshold (default: `1`).
    - `decimal?`: Decimal configuration (fixed number or range format).
    - `highPrecision?`: Enables `decimal.js` for precise calculations.

### **Methods**

###### `getUnit(num: Num<DS>)`

Gets the optimal unit and converted value from base units.

- **Parameters**:
  - `num`: Input number. Supports `number`, `string`, `BigInt`, and `Decimal` in high-precision mode.

- **Returns**:
  - `{ num: number, unit: string, decimal: Decimal }`: Converted value with unit. Includes `Decimal` in high-precision mode.

###### `format(num: Num<DS>, decimal = this.decimal)`

Formats a number into a unit-string representation.

- **Parameters**:
  - `num`: Input number (supports extended types in high-precision mode).
  - `decimal?`: Overrides default decimal configuration.

- **Returns**:
  - Formatted string with value and unit.

###### `toBase(num: Num<DS>, unit: string)`

Converts a unit-formatted number back to base units.

- **Parameters**:
  - `num`: Input value in specified unit.
  - `unit`: Current unit.

- **Returns**:
  - Converted value in base units (`number` or `Decimal`).

###### `splitUnit(str: string)`

Extracts numeric value and unit from a string.

- **Parameters**:
  - `str`: Input string containing value and unit.

- **Returns**:
  - `{ num: number, unit: string, decimal: Decimal }`: Parsed components with `Decimal` in high-precision mode.

###### `parse(str: string)`

Converts a unit-formatted string to base unit value.

- **Parameters**:
  - `str`: Input string.

- **Returns**:
  - Converted value in base units (`number` or `Decimal`).

###### `fromUnitFormat(num: number, unit: string, decimal?: DecimalPlace)`

Converts between units and formats with specified decimals.

- **Parameters**:
  - `num`: Input value.
  - `unit`: Source unit.
  - `decimal?`: Overrides default decimal configuration.

- **Returns**:
  - Formatted string with converted value and unit.

## Contributing

Contributions of all forms are welcome, including bug reports, documentation improvements, translation updates, and test enhancements.

---
_Source: https://npm.io/package/auto-unit · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
