numbers_it.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import { Grammar } from '../../rule_engine/grammar.js';
  2. import { NUMBERS as NUMB } from '../messages.js';
  3. function hundredsToWords_(num) {
  4. let n = num % 1000;
  5. let str = '';
  6. str += NUMBERS.ones[Math.floor(n / 100)]
  7. ? NUMBERS.ones[Math.floor(n / 100)] + NUMBERS.numSep + 'cento'
  8. : '';
  9. n = n % 100;
  10. if (n) {
  11. str += str ? NUMBERS.numSep : '';
  12. const ones = NUMBERS.ones[n];
  13. if (ones) {
  14. str += ones;
  15. }
  16. else {
  17. let tens = NUMBERS.tens[Math.floor(n / 10)];
  18. const rest = n % 10;
  19. if (rest === 1 || rest === 8) {
  20. tens = tens.slice(0, -1);
  21. }
  22. str += tens;
  23. str += rest ? NUMBERS.numSep + NUMBERS.ones[n % 10] : '';
  24. }
  25. }
  26. return str;
  27. }
  28. function numberToWords(num) {
  29. if (num === 0) {
  30. return NUMBERS.zero;
  31. }
  32. if (num >= Math.pow(10, 36)) {
  33. return num.toString();
  34. }
  35. if (num === 1 && Grammar.getInstance().getParameter('fraction')) {
  36. return 'un';
  37. }
  38. let pos = 0;
  39. let str = '';
  40. while (num > 0) {
  41. const hundreds = num % 1000;
  42. if (hundreds) {
  43. str =
  44. hundredsToWords_(num % 1000) +
  45. (pos ? '-' + NUMBERS.large[pos] + '-' : '') +
  46. str;
  47. }
  48. num = Math.floor(num / 1000);
  49. pos++;
  50. }
  51. return str.replace(/-$/, '');
  52. }
  53. function numberToOrdinal(num, plural) {
  54. if (num === 2) {
  55. return plural ? 'mezzi' : 'mezzo';
  56. }
  57. const ordinal = wordOrdinal(num);
  58. if (!plural) {
  59. return ordinal;
  60. }
  61. const gender = ordinal.match(/o$/) ? 'i' : 'e';
  62. return ordinal.slice(0, -1) + gender;
  63. }
  64. function wordOrdinal(num) {
  65. const gender = Grammar.getInstance().getParameter('gender');
  66. const postfix = gender === 'm' ? 'o' : 'a';
  67. let ordinal = NUMBERS.special.onesOrdinals[num];
  68. if (ordinal) {
  69. return ordinal.slice(0, -1) + postfix;
  70. }
  71. ordinal = numberToWords(num);
  72. return ordinal.slice(0, -1) + 'esim' + postfix;
  73. }
  74. function numericOrdinal(num) {
  75. const gender = Grammar.getInstance().getParameter('gender');
  76. return num.toString() + (gender === 'm' ? 'o' : 'a');
  77. }
  78. export const NUMBERS = NUMB({
  79. wordOrdinal: wordOrdinal,
  80. numericOrdinal: numericOrdinal,
  81. numberToWords: numberToWords,
  82. numberToOrdinal: numberToOrdinal
  83. });