repl.it
@dhruvdutt/

number-to-words util

Nodejs

No description

fork
loading
Files
  • index.js
  • Packager files
  • package-lock.json
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
const numberToWords = require("number-to-words");
const _startCase = require('lodash/startCase');

// cybertron-utils START

const pluralize = (
  amount,
  singularForm,
  pluralForm = `${singularForm}s`,
) => {
  let word = '';

  if (+amount === 1) {
    word = singularForm;
  } else {
    word = pluralForm;
  }

  return word;
};

const startCase = (value) => {
  if (typeof value === 'string') {
    return _startCase(value.toLowerCase());
  }
  return _startCase(value);
};

const toTwoDecimals = (amount) => {
  const parsedFloat = parseFloat(amount);
  const fixedString = parsedFloat.toFixed(2);
  return fixedString;
};

const toAmount = (currency) => {
  if (
    typeof currency !== 'string' &&
    typeof currency !== 'number'
  ) {
    return NaN;
  }
  const fixedString = toTwoDecimals(currency);
  return parseFloat(fixedString);
};

// cybertron-utils END

const currencyToWords = (amount) => {
  const [integerPartStr, fractionPartStr] = String(amount.toFixed(2)).split('.');
  const integerPart = toAmount(integerPartStr);
  const fractionPart = toAmount(fractionPartStr);
  let amountToWords = '';

  amountToWords += `${numberToWords.toWords(integerPart)} `;
  amountToWords += pluralize(integerPart, 'Rupee');

  if (fractionPart) {
    amountToWords += ` and ${numberToWords.toWords(fractionPart)} `;
    amountToWords += pluralize(fractionPart, 'Paisa', 'Paise');
  }

  return startCase(amountToWords);
}

console.log(currencyToWords(01));
console.log(currencyToWords(100));
console.log(currencyToWords(100.0));
console.log(currencyToWords(100.00));
console.log(currencyToWords(100.1));
console.log(currencyToWords(100.01));
console.log(currencyToWords(125.555));