Documentation for this module may be created at Module:NumberSpell/doc

  1. -- This module converts a number into its written English form.
  2. -- For example, "2" becomes "two", and "79" becomes "seventy-nine".
  3.  
  4. local getArgs = require('Module:Arguments').getArgs
  5.  
  6. local p = {}
  7.  
  8. local max = 100 -- The maximum number that can be parsed.
  9.  
  10. local ones = {
  11. [0] = 'zero',
  12. [1] = 'one',
  13. [2] = 'two',
  14. [3] = 'three',
  15. [4] = 'four',
  16. [5] = 'five',
  17. [6] = 'six',
  18. [7] = 'seven',
  19. [8] = 'eight',
  20. [9] = 'nine'
  21. }
  22.  
  23. local specials = {
  24. [10] = 'ten',
  25. [11] = 'eleven',
  26. [12] = 'twelve',
  27. [13] = 'thirteen',
  28. [15] = 'fifteen',
  29. [18] = 'eighteen',
  30. [20] = 'twenty',
  31. [30] = 'thirty',
  32. [40] = 'forty',
  33. [50] = 'fifty',
  34. [60] = 'sixty',
  35. [70] = 'seventy',
  36. [80] = 'eighty',
  37. [90] = 'ninety',
  38. [100] = 'one hundred'
  39. }
  40.  
  41. local formatRules = {
  42. {num = 90, rule = 'ninety-%s'},
  43. {num = 80, rule = 'eighty-%s'},
  44. {num = 70, rule = 'seventy-%s'},
  45. {num = 60, rule = 'sixty-%s'},
  46. {num = 50, rule = 'fifty-%s'},
  47. {num = 40, rule = 'forty-%s'},
  48. {num = 30, rule = 'thirty-%s'},
  49. {num = 20, rule = 'twenty-%s'},
  50. {num = 10, rule = '%steen'}
  51. }
  52.  
  53. function p.main(frame)
  54. local args = getArgs(frame)
  55. local num = tonumber(args[1])
  56. local success, result = pcall(p._main, num)
  57. if success then
  58. return result
  59. else
  60. return string.format('<strong class="error">Error: %s</strong>', result) -- "result" is the error message.
  61. end
  62. return p._main(num)
  63. end
  64.  
  65. function p._main(num)
  66. if type(num) ~= 'number' or math.floor(num) ~= num or num < 0 or num > max then
  67. error('input must be an integer between 0 and ' .. tostring(max), 2)
  68. end
  69. -- Check for numbers from 0 to 9.
  70. local onesVal = ones[num]
  71. if onesVal then
  72. return onesVal
  73. end
  74. -- Check for special numbers.
  75. local specialVal = specials[num]
  76. if specialVal then
  77. return specialVal
  78. end
  79. -- Construct the number from its format rule.
  80. onesVal = ones[num % 10]
  81. if not onesVal then
  82. error('Unexpected error parsing input ' .. tostring(num))
  83. end
  84. for i, t in ipairs(formatRules) do
  85. if num >= t.num then
  86. return string.format(t.rule, onesVal)
  87. end
  88. end
  89. error('No format rule found for input ' .. tostring(num))
  90. end
  91.  
  92. return p