New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

to-numbers

Package Overview
Dependencies
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

to-numbers

Converts words (including decimal points) into numbers & currency. The reverse of to-words.

latest
Source
npmnpm
Version
1.0.0
Version published
Maintainers
1
Created
Source

to-numbers

npm version npm downloads build coverage minzipped size TypeScript license

Convert words to numbers with comprehensive locale, currency, and decimal support. The reverse of the to-words package. Ideal for parsing written amounts in invoicing, voice input, e-commerce, and financial applications.

📑 Table of Contents

💼 Use Cases

  • Financial Applications — Parse amount-in-words from invoices, cheques, and financial documents
  • Voice/Speech Input — Convert spoken numbers from speech-to-text to numeric values
  • Data Processing — Extract numeric data from textual documents and forms
  • OCR Post-Processing — Parse numbers recognized from scanned documents
  • Chatbots & NLP — Understand numeric inputs in natural language
  • Accessibility — Support users who input numbers as words
  • Localization — Parse numbers in 94 different languages and regions

✨ Features

  • 94 Locales — The most comprehensive locale coverage available
  • High Performance — Up to 3.7M ops/sec with optimized parsing algorithms
  • Reverse of to-words — Perfectly complements the to-words package
  • Multiple Numbering Systems — Short scale, Long scale, Indian, and East Asian
  • Currency Parsing — Parse locale-specific currency with fractional units
  • Ordinal Numbers — Parse ordinals like "First", "Twenty Third", "Hundredth"
  • Decimal Numbers — Handle "Point" notation and fractional units
  • Case Insensitive — Works with any case combination
  • Tree-Shakeable — Import only the locales you need
  • TypeScript Native — Full type definitions included
  • Multiple Formats — ESM, CommonJS, and UMD browser bundles
  • Zero Dependencies — Lightweight and self-contained

⚡ Performance

Optimized for high-throughput parsing with minimal memory allocation:

Input TypeExampleOperations/sec
Small Integer"Forty Two"~3.7M ops/sec
Medium Integer"Twelve Thousand Three Hundred Forty Five"~1.6M ops/sec
Large Integer"Nine Trillion Eight Hundred Seventy Six Billion..."~500K ops/sec
Currency"One Thousand Two Hundred Rupees And Fifty Paise"~875K ops/sec
Ordinal"Twenty Third"~1.8M ops/sec

Benchmarks run on Apple M1 using Vitest bench. Run npm run bench to test on your hardware.

🚀 Quick Start

import { ToNumbers } from 'to-numbers';

const toNumbers = new ToNumbers();
toNumbers.convert('Twelve Thousand Three Hundred Forty Five');
// 12345

📦 Installation

npm / yarn / pnpm

npm install to-numbers
# or
yarn add to-numbers
# or
pnpm add to-numbers

CDN (Browser)

<!-- Full bundle with all locales -->
<script src="https://cdn.jsdelivr.net/npm/to-numbers/dist/umd/to-numbers.min.js"></script>

<!-- Single locale bundle (smaller, recommended) -->
<script src="https://cdn.jsdelivr.net/npm/to-numbers/dist/umd/en-US.min.js"></script>

📖 Usage

Importing

// ESM
import { ToNumbers } from 'to-numbers';

// CommonJS
const { ToNumbers } = require('to-numbers');

Basic Conversion

const toNumbers = new ToNumbers({ localeCode: 'en-US' });

toNumbers.convert('One Hundred Twenty Three');
// 123

toNumbers.convert('One Hundred Twenty Three Point Four Five');
// 123.45

toNumbers.convert('Minus Fifty');
// -50

Case Insensitivity

const toNumbers = new ToNumbers({ localeCode: 'en-US' });

toNumbers.convert('one hundred twenty three');
// 123

toNumbers.convert('ONE HUNDRED TWENTY THREE');
// 123

toNumbers.convert('One Hundred Twenty Three');
// 123

Ordinal Numbers

Parse ordinal words automatically — no special options needed:

const toNumbers = new ToNumbers({ localeCode: 'en-US' });

toNumbers.convert('First');
// 1

toNumbers.convert('Twenty Third');
// 23

toNumbers.convert('One Hundredth');
// 100

toNumbers.convert('One Thousand Two Hundred Thirty Fourth');
// 1234

Currency Parsing

const toNumbers = new ToNumbers({ localeCode: 'en-IN' });

toNumbers.convert('Four Hundred Fifty Two Rupees Only', { currency: true });
// 452

toNumbers.convert('Four Hundred Fifty Two Rupees And Thirty Six Paise Only', { currency: true });
// 452.36

// Works without "Only" suffix too
toNumbers.convert('Four Hundred Fifty Two Rupees', { currency: true });
// 452

// Fractional units only
toNumbers.convert('Thirty Six Paise Only', { currency: true });
// 0.36

Custom Currency

Override currency settings while keeping the locale's language:

const toNumbers = new ToNumbers({
  localeCode: 'en-US',
  converterOptions: {
    currency: true,
    currencyOptions: {
      name: 'Euro',
      plural: 'Euros',
      symbol: '€',
      fractionalUnit: {
        name: 'Cent',
        plural: 'Cents',
        symbol: '',
      },
    },
  },
});

toNumbers.convert('One Hundred Euros And Fifty Cents Only');
// 100.50

Tree-Shakeable Imports

Import only the locales you need for smaller bundle sizes:

// Import specific locale directly (includes ToNumbers configured for that locale)
import { ToNumbers } from 'to-numbers/en-US';

const toNumbers = new ToNumbers();
toNumbers.convert('Twelve Thousand Three Hundred Forty Five');
// 12345

Browser Usage (UMD)

<!-- Single locale (recommended, smaller bundle) -->
<script src="https://cdn.jsdelivr.net/npm/to-numbers/dist/umd/en-US.min.js"></script>
<script>
  // ToNumbers is pre-configured for en-US
  const toNumbers = new ToNumbers();
  console.log(toNumbers.convert('Twelve Thousand'));
  // 12000
</script>

<!-- Full bundle with all locales -->
<script src="https://cdn.jsdelivr.net/npm/to-numbers/dist/umd/to-numbers.min.js"></script>
<script>
  // Specify locale when using full bundle
  const toNumbers = new ToNumbers({ localeCode: 'fr-FR' });
  console.log(toNumbers.convert('Douze Mille'));
  // 12000
</script>

⚛️ Framework Integration

React

import { ToNumbers } from 'to-numbers/en-US';

const toNumbers = new ToNumbers();

function ParsedAmount({ text }: { text: string }) {
  const amount = toNumbers.convert(text, { currency: true });
  return <span className="amount">${amount.toFixed(2)}</span>;
}

// Usage: <ParsedAmount text="One Thousand Two Hundred Thirty Four Dollars" />
// Renders: $1234.00

Vue 3

<script setup lang="ts">
import { computed } from 'vue';
import { ToNumbers } from 'to-numbers/en-US';

const props = defineProps<{ text: string }>();
const toNumbers = new ToNumbers();

const amount = computed(() =>
  toNumbers.convert(props.text, { currency: true })
);
</script>

<template>
  <span class="amount">${{ amount.toFixed(2) }}</span>
</template>

Angular

import { Pipe, PipeTransform } from '@angular/core';
import { ToNumbers } from 'to-numbers/en-US';

@Pipe({ name: 'toNumbers', standalone: true })
export class ToNumbersPipe implements PipeTransform {
  private toNumbers = new ToNumbers();

  transform(value: string, currency = false): number {
    return this.toNumbers.convert(value, { currency });
  }
}

// Usage: {{ 'One Thousand Dollars' | toNumbers:true }}

Svelte

<script lang="ts">
  import { ToNumbers } from 'to-numbers/en-US';
  
  export let text: string;
  
  const toNumbers = new ToNumbers();
  $: amount = toNumbers.convert(text, { currency: true });
</script>

<span class="amount">${amount.toFixed(2)}</span>

🌍 Numbering Systems

Different regions use different numbering systems. This library supports all major systems:

Short Scale (Western)

Used in: USA, UK, Canada, Australia, and most English-speaking countries.

NumberName
10^6Million
10^9Billion
10^12Trillion
10^15Quadrillion
const toNumbers = new ToNumbers({ localeCode: 'en-US' });
toNumbers.convert('One Quintillion');
// 1000000000000000000

Long Scale (European)

Used in: Germany, France, and many European countries.

NumberGermanFrench
10^6MillionMillion
10^9MilliardeMilliard
10^12BillionBillion
const toNumbers = new ToNumbers({ localeCode: 'de-DE' });
toNumbers.convert('Eins Milliarde');
// 1000000000

Indian System

Used in: India, Bangladesh, Nepal, Pakistan.

NumberName
10^5Lakh
10^7Crore
10^9Arab
10^11Kharab
10^13Neel
10^15Padma
10^17Shankh
const toNumbers = new ToNumbers({ localeCode: 'en-IN' });
toNumbers.convert('Five Lakh Twenty Three Thousand');
// 523000

toNumbers.convert('Two Crore Fifty Lakh');
// 25000000

const toNumbersHindi = new ToNumbers({ localeCode: 'hi-IN' });
toNumbersHindi.convert('एक करोड़');
// 10000000

East Asian System

Used in: Japan, China, Korea.

NumberCharacter
10^4万 (Man/Wan)
10^8億 (Oku/Yi)
10^12兆 (Chō/Zhao)
const toNumbers = new ToNumbers({ localeCode: 'ko-KR' });
toNumbers.convert('일억');
// 100000000

⚙️ API Reference

Constructor Options

interface ToNumbersOptions {
  localeCode?: string;           // Default: 'en-IN'
  converterOptions?: {
    currency?: boolean;          // Default: false (auto-detect when undefined)
    currencyOptions?: {          // Override locale's currency settings
      name: string;
      plural: string;
      symbol: string;
      fractionalUnit: {
        name: string;
        plural: string;
        symbol: string;
      };
    };
  };
}

Methods

convert(text, options?)

Converts words to a number.

  • text: string — The text containing number words to convert
  • options: ConverterOptions — Override instance options
  • returns: number — The parsed numeric value
const toNumbers = new ToNumbers({ localeCode: 'en-US' });

toNumbers.convert('One Hundred Twenty Three');
// 123

toNumbers.convert('Fifty Dollars Only', { currency: true });
// 50

Converter Options

OptionTypeDefaultDescription
currencybooleanfalseParse as currency with locale-specific formatting
currencyOptionsobjectundefinedOverride locale's default currency settings

📏 Bundle Sizes

Import MethodRawGzip
Full bundle (all 94 locales)~500 KB~50 KB
Single locale (en-US)~10 KB~3 KB
Single locale (en-IN)~9 KB~3 KB

Tip: Use tree-shakeable imports or single-locale UMD bundles for the smallest bundle size.

🌐 Browser Compatibility

BrowserVersion
Chrome49+
Firefox52+
Safari10+
Edge14+
Opera36+

🗺️ Supported Locales

All 94 locales with their features:

LocaleLanguageCountryCurrencyScale
af-ZAAfrikaansSouth AfricaRandShort
am-ETAmharicEthiopiaብርShort
ar-AEArabicUAEدرهمShort
ar-LBArabicLebanonليرةShort
ar-MAArabicMoroccoدرهمShort
ar-SAArabicSaudi ArabiaريالShort
az-AZAzerbaijaniAzerbaijanManatShort
be-BYBelarusianBelarusРубельShort
bg-BGBulgarianBulgariaЛевShort
bn-INBengaliIndiaটাকাIndian
ca-ESCatalanSpainEuroShort
cs-CZCzechCzech RepublicKorunaShort
da-DKDanishDenmarkKroneLong
de-DEGermanGermanyEuroLong
ee-EEEstonianEstoniaEuroShort
el-GRGreekGreeceΕυρώShort
en-AEEnglishUAEDirhamShort
en-AUEnglishAustraliaDollarShort
en-BDEnglishBangladeshTakaIndian
en-CAEnglishCanadaDollarShort
en-GBEnglishUnited KingdomPoundShort
en-GHEnglishGhanaCediShort
en-IEEnglishIrelandEuroShort
en-INEnglishIndiaRupeeIndian
en-KEEnglishKenyaShillingShort
en-MAEnglishMoroccoDirhamShort
en-MMEnglishMyanmarKyatShort
en-MUEnglishMauritiusRupeeIndian
en-MYEnglishMalaysiaRinggitShort
en-NGEnglishNigeriaNairaShort
en-NPEnglishNepalRupeeIndian
en-NZEnglishNew ZealandDollarShort
en-OMEnglishOmanRialShort
en-PHEnglishPhilippinesPesoShort
en-PKEnglishPakistanRupeeIndian
en-SAEnglishSaudi ArabiaRiyalShort
en-SGEnglishSingaporeDollarShort
en-USEnglishUSADollarShort
en-ZAEnglishSouth AfricaRandShort
es-ARSpanishArgentinaPesoShort
es-ESSpanishSpainEuroShort
es-MXSpanishMexicoPesoShort
es-USSpanishUSADólarShort
es-VESpanishVenezuelaBolívarShort
fa-IRPersianIranتومانShort
fi-FIFinnishFinlandEuroShort
fil-PHFilipinoPhilippinesPisoShort
fr-BEFrenchBelgiumEuroLong
fr-FRFrenchFranceEuroLong
fr-MAFrenchMoroccoDirhamLong
fr-SAFrenchSaudi ArabiaRiyalLong
gu-INGujaratiIndiaરૂપિયોIndian
ha-NGHausaNigeriaNairaShort
hbo-ILBiblical HebrewIsraelשקלShort
he-ILHebrewIsraelשקלShort
hi-INHindiIndiaरुपयाIndian
hr-HRCroatianCroatiaEuroShort
hu-HUHungarianHungaryForintShort
id-IDIndonesianIndonesiaRupiahShort
is-ISIcelandicIcelandKrónaShort
it-ITItalianItalyEuroShort
ja-JPJapaneseJapanEast Asian
ka-GEGeorgianGeorgiaლარიShort
kn-INKannadaIndiaರೂಪಾಯಿIndian
ko-KRKoreanSouth KoreaShort
lt-LTLithuanianLithuaniaEurasShort
lv-LVLatvianLatviaEiroShort
mr-INMarathiIndiaरुपयाIndian
ms-MYMalayMalaysiaRinggitShort
nb-NONorwegianNorwayKroneLong
nl-NLDutchNetherlandsEuroShort
nl-SRDutchSurinameDollarShort
np-NPNepaliNepalरुपैयाँIndian
pa-INPunjabiIndiaਰੁਪਇਆIndian
pl-PLPolishPolandZłotyShort
pt-BRPortugueseBrazilRealShort
pt-PTPortuguesePortugalEuroShort
ro-RORomanianRomaniaLeuShort
ru-RURussianRussiaРубльShort
sk-SKSlovakSlovakiaEuroShort
sl-SISlovenianSloveniaEuroShort
sq-ALAlbanianAlbaniaLekShort
sr-RSSerbianSerbiaDinarShort
sv-SESwedishSwedenKronaShort
sw-KESwahiliKenyaShilingiShort
ta-INTamilIndiaரூபாய்Indian
te-INTeluguIndiaరూపాయిIndian
th-THThaiThailandบาทShort
tr-TRTurkishTurkeyLiraShort
uk-UAUkrainianUkraineГривняShort
ur-PKUrduPakistanروپیہIndian
vi-VNVietnameseVietnamĐồngShort
yo-NGYorubaNigeriaNairaShort
zh-CNChineseChinaEast Asian

Scale Legend:

  • Short — Western short scale (Million, Billion, Trillion...)
  • Long — European long scale (Million, Milliard, Billion, Billiard...)
  • Indian — Indian numbering (Lakh, Crore, Arab, Kharab...)
  • East Asian — East Asian numbering (万, 億, 兆, 京...)

⚠️ Error Handling

The library throws descriptive errors for invalid inputs:

Invalid Input

const toNumbers = new ToNumbers();

toNumbers.convert('');
// Error: Invalid Input ""

toNumbers.convert('   ');
// Error: Invalid Input "   "

Unknown Locale

const toNumbers = new ToNumbers({ localeCode: 'xx-XX' });
toNumbers.convert('One');
// Error: Unknown Locale "xx-XX"

Handling Errors

try {
  const amount = toNumbers.convert(userInput, { currency: true });
  console.log('Parsed amount:', amount);
} catch (error) {
  console.error('Parsing failed:', error.message);
}

🤝 Contributing

Adding a New Locale

  • Create the locale file: Add src/locales/<locale-code>.ts implementing LocaleInterface from src/types.ts. Use an existing locale as a template.

  • Register the locale: Import your class in src/locales/index.ts and add it to the LOCALES map.

  • Add tests: Create __tests__/<locale-code>.test.ts covering integers, negatives, decimals, and currency parsing.

  • Update documentation: Add the locale to the Supported Locales section above.

  • Build and test: Run npm test and npm run build, then submit your PR.

❓ FAQ

How does this relate to the to-words package?

to-numbers is the reverse of to-words. While to-words converts 123"One Hundred Twenty Three", to-numbers converts "One Hundred Twenty Three"123.

They share the same locale support and are designed to work together:

import { ToWords } from 'to-words';
import { ToNumbers } from 'to-numbers';

const toWords = new ToWords({ localeCode: 'en-US' });
const toNumbers = new ToNumbers({ localeCode: 'en-US' });

const words = toWords.convert(12345);
// "Twelve Thousand Three Hundred Forty Five"

const number = toNumbers.convert(words);
// 12345 ✓ Round-trip complete!
Is parsing case-sensitive?

No! The parser is fully case-insensitive:

toNumbers.convert('one hundred');      // 100
toNumbers.convert('ONE HUNDRED');      // 100
toNumbers.convert('One Hundred');      // 100
toNumbers.convert('oNe HuNdReD');      // 100
Can I parse currency from different locales?

Yes! Each locale has its own currency configuration:

// Indian Rupees
const tnIN = new ToNumbers({ localeCode: 'en-IN' });
tnIN.convert('Five Hundred Rupees Only', { currency: true });
// 500

// US Dollars
const tnUS = new ToNumbers({ localeCode: 'en-US' });
tnUS.convert('Five Hundred Dollars Only', { currency: true });
// 500

// French Euros
const tnFR = new ToNumbers({ localeCode: 'fr-FR' });
tnFR.convert('Cinq Cents Euros', { currency: true });
// 500
Does this work in the browser?

Yes! Use the UMD bundles via CDN:

<script src="https://cdn.jsdelivr.net/npm/to-numbers/dist/umd/en-US.min.js"></script>
<script>
  const toNumbers = new ToNumbers();
  console.log(toNumbers.convert('One Hundred Twenty Three'));
  // 123
</script>
How do I add support for a new locale?

See the Contributing section above. You'll need to create a locale file implementing the LocaleInterface and add tests.

What about ordinal numbers (First, Second, Third)?

Ordinal parsing is fully supported! The library automatically detects ordinal words:

toNumbers.convert('First');        // 1
toNumbers.convert('Twenty Third'); // 23
toNumbers.convert('Hundredth');    // 100

Ordinal support is available for English locales. Other locales are being added progressively.

📋 Changelog

See CHANGELOG.md for a detailed history of changes.

📄 License

MIT

Keywords

to numbers

FAQs

Package last updated on 03 Feb 2026

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts