DEV Community

Cris Mihalache
Cris Mihalache

Posted on

A Tiny JS Library For Parsing Numbers From Words

After encountering the need to parse numbers written out as strings with multiple words for a project (i.e., "twenty-two days ago" as opposed to "22 days ago"), I went ahead and developed a tiny, zero-dependency library that does exactly that.

I've christened it numbers-from-words, and will be using it in my time tracker project.

Here is a short snippet showing a few input types:

import { parse } from 'numbers-from-words'

const valueA = parse('twenty')
const valueB = parse('one hundred and twenty three')
const valueC = parse('one thousand, two hundred and thirty four')

console.log({
    valueA,  // 20
    valueB,  // 123
    valueC   // 1234
})
Enter fullscreen mode Exit fullscreen mode

Parsing is relatively simple, and the logic can be found here. In short, it supports any valid written representation of a number, which is usually a quantity followed by a magnitude (i.e. "two months" or "twenty five years").

Commas dividing the string for more complex written numbers are also supported, such as "twenty-five, one hundred, and three thousand" (parsed to 3125).

It categorizes number words into Numbers, Teens, Multiples, and Magnitudes. These are the available (and therefore supported) values:

export enum Numbers {
  Zero = 0,
  One = 1,
  Two = 2,
  Three = 3,
  Four = 4,
  Five = 5,
  Six = 6,
  Seven = 7,
  Eight = 8,
  Nine = 9
}

export enum Teens {
  Ten = 10,
  Eleven = 11,
  Twelve = 12,
  Thirteen = 13,
  Fourteen = 14,
  Fifteen = 15,
  Sixteen = 16,
  Seventeen = 17,
  Eighteen = 18,
  Nineteen = 19
}

export enum Multiples {
  Twenty = 20,
  Thirty = 30,
  Forty = 40,
  Fifty = 50,
  Sixty = 60,
  Seventy = 70,
  Eighty = 80,
  Ninety = 90
}

export enum Magnitudes {
  Hundred = 100,
  Thousand = 1000,
  Million = 1000000,
  Billion = 1000000000,
  Trillion = 1000000000000,
  Quadrillion = 1000000000000000
}
Enter fullscreen mode Exit fullscreen mode

For more information, check out the README.md and the GitHub repo itself.

Top comments (0)