Skip to content

Instantly share code, notes, and snippets.

@RubenVerg
Created May 22, 2020 10:52
Show Gist options
  • Save RubenVerg/3427217c04798388782ef99bf86cf64a to your computer and use it in GitHub Desktop.
Save RubenVerg/3427217c04798388782ef99bf86cf64a to your computer and use it in GitHub Desktop.
number to italian numeral
let nTI = {}
nTI.map = {
'-': 'meno',
0: 'zero',
1: ['uno', 'un'],
2: 'due',
3: 'tre',
4: 'quattro',
5: 'cinque',
6: 'sei',
7: 'sette',
8: 'otto',
9: 'nove',
10: 'dieci',
11: 'undici',
12: 'dodici',
13: 'tredici',
14: 'quattordici',
15: 'quindici',
16: 'sedici',
17: 'diciassette',
18: 'diciotto',
19: 'diciannove',
20: ['venti', 'vent'],
30: ['trenta', 'trent'],
40: ['quaranta', 'quarant'],
50: ['cinquanta', 'cinquant'],
60: ['sessanta', 'sessant'],
70: ['settanta', 'settant'],
80: ['ottanta', 'ottant'],
90: ['novanta', 'novant'],
100: 'cento',
1000: ['mille', 'mila'],
1_000_000: ['milione', 'milioni'],
1_000_000_000: ['miliardo', 'miliardi'],
1_000_000_000_000: ['bilione', 'bilioni'],
useShort: [1, 8],
}
nTI.simple = num => {
const hundreds = (num.toString().length == 3) ? parseInt(num.toString()[0]) : 0;
const tens = (num.toString().length == 3) ? parseInt(num.toString()[1]) :
(num.toString().length == 2) ? parseInt(num.toString()[0]) : 0;
const units = parseInt(num.toString()[num.toString().length - 1]);
let res = '';
if (hundreds) {
if (hundreds === 1) {
res += nTI.map[100];
} else {
res += nTI.map[parseInt(hundreds)] + nTI.map[100];
}
}
if (typeof (nTI.map[tens * 10 + units]) == 'string') {
res += nTI.map[tens * 10 + units];
} else if (tens) {
if (nTI.map.useShort.indexOf(units) !== -1) {
res += nTI.map[tens * 10][1] + nTI.map[units];
} else {
res += nTI.map[tens * 10][0] + nTI.map[units];
}
} else {
res += (units == 1) ? nTI.map[units][0] : nTI.map[units];
}
if (res.substr(-4) == 'zero')
res = res.substr(0, res.length - 4)
return res;
}
nTI.units = nTI.simple;
nTI.kilos = kilos => {
if (kilos == 1)
return nTI.map[1000][0];
else
return nTI.simple(kilos) + nTI.map[1000][1];
}
nTI.over = (mils, name) => {
if (mils == 1)
return nTI.map[1][1] + ' ' + name[0];
else
return nTI.simple(mils) + ' ' + name[1];
}
nTI.translate = num => {
let out = '';
const string = num.toString().padStart((num.toString().length + num.toString().length % 3), '0');
const pieces = string.match(/.{3}/g).map(i => +i).reverse();
for (let ind = pieces.length - 1; ind >= 0; ind--) {
if (ind === 0) {
out += nTI.units(pieces[ind]);
} else if (ind === 1) {
out += nTI.kilos(pieces[ind]) + ' ';
} else {
const a = parseInt('1' + '0'.repeat(3 * ind));
out += nTI.over(pieces[ind], a) + ' e ';
}
}
for (let index = 0; index < pieces.length; index++) {
const element = pieces[index];
if (index == 0)
out = out + nTI.units(element);
}
return out;
}
// Node Export
if (process) {
module.exports = nTI;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment