Skip to content

Instantly share code, notes, and snippets.

@geekyorion
Created October 28, 2022 15:02
Show Gist options
  • Save geekyorion/60a9168e05b22948eb2c91ef7dd0e05c to your computer and use it in GitHub Desktop.
Save geekyorion/60a9168e05b22948eb2c91ef7dd0e05c to your computer and use it in GitHub Desktop.

Revisions

  1. geekyorion created this gist Oct 28, 2022.
    98 changes: 98 additions & 0 deletions numberToWord_en_IN.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,98 @@
    const numberTexts = {
    0: 'zero',
    1: 'one',
    2: 'two',
    3: 'three',
    4: 'four',
    5: 'five',
    6: 'six',
    7: 'seven',
    8: 'eight',
    9: 'nine',
    10: 'ten',
    11: 'eleven',
    12: 'twelve',
    13: 'thirteen',
    14: 'fourteen',
    15: 'fifteen',
    16: 'sixteen',
    17: 'seventeen',
    18: 'eighteen',
    19: 'nineteen',
    20: 'twenty',
    30: 'thirty',
    40: 'forty',
    50: 'fifty',
    60: 'sixty',
    70: 'seventy',
    80: 'eighty',
    90: 'ninety',
    100: 'hundred',
    1000: 'thousand',
    100000: 'lakhs',
    10000000: 'Crores'
    };

    const checkLimit = number => {
    const upperLimit = 999999999;
    if (number > upperLimit) {
    throw new Error(`number should be less than ${upperLimit}`);
    }
    };

    const getLastNDigits = (num, power) => {
    const divider = 10 ** power;
    return [num % divider, ~~(num / divider)];
    };

    const getTwoDigitWord = digits => {
    let word = '';
    if (digits in numberTexts) {
    word = numberTexts[digits];
    } else {
    const [remaining, tensPlace] = getLastNDigits(digits, 1);
    word = `${numberTexts[tensPlace * 10]} ${numberTexts[remaining]}`;
    }
    return word;
    };

    const getWordPlace = place => {
    if (place) {
    return numberTexts[10 ** place];
    }
    return '';
    }

    const getDigitWithPlace = (digit, place) => {
    const wordPlace = getWordPlace(place);
    if (digit < 10) {
    return `${numberTexts[digit]} ${wordPlace}`;
    }
    return `${getTwoDigitWord(digit)} ${wordPlace}`;
    }

    const getText = number => {
    checkLimit(number);

    let _number = number;
    let currentDigits = _number;

    if (_number in numberTexts) {
    return numberTexts[_number];
    } else {
    const checkFor = [2, 1, 2, 2, 2];
    const places = [0, 2, 3, 5, 7];
    let word = '';

    for (let i in checkFor) {
    [currentDigits, _number] = getLastNDigits(_number, checkFor[i]);
    if (currentDigits) {
    word = `${getDigitWithPlace(currentDigits, places[i])} ${word}`;
    }
    if (!_number) return word.trim();
    }
    }
    };

    const text = getText(1111);
    console.log(text); // one thousand one hundred eleven