-
Notifications
You must be signed in to change notification settings - Fork 0
/
number2word.go
119 lines (94 loc) · 2.38 KB
/
number2word.go
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package number2word
import (
"math"
)
const groupsNumber int = 4
var _smallNumbers = []string{
"zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine",
"ten", "eleven", "twelve", "thirteen", "fourteen",
"fifteen", "sixteen", "seventeen", "eighteen", "nineteen",
}
var _tens = []string{
"", "", "twenty", "thirty", "forty", "fifty",
"sixty", "seventy", "eighty", "ninety",
}
var _scaleNumbers = []string{
"", "thousand", "million", "billion",
}
type digitGroup int
// Convert converts number into the words representation.
func Convert(number int) (string, error) {
return convertText(number, false)
}
// ConvertAnd converts number into the words representation
// with " and " added between number groups.
func ConvertAnd(number int) (string, error) {
return convertText(number, true)
}
func convertText(number int, useAnd bool) (string, error) {
// Zero rule
if number == 0 {
return _smallNumbers[0], nil
}
// Divide into three-digits group
var groups [groupsNumber]digitGroup
positive := math.Abs(float64(number))
// Form three-digit groups
for i := 0; i < groupsNumber; i++ {
groups[i] = digitGroup(math.Mod(positive, 1000))
positive /= 1000
}
var textGroup [groupsNumber]string
for i := 0; i < groupsNumber; i++ {
textGroup[i] = digitGroup2Text(groups[i], useAnd)
}
combined := textGroup[0]
and := useAnd && (groups[0] > 0 && groups[0] < 100)
for i := 1; i < groupsNumber; i++ {
if groups[i] != 0 {
prefix := textGroup[i] + " " + _scaleNumbers[i]
if len(combined) != 0 {
prefix += separator(and)
}
and = false
combined = prefix + combined
}
}
if number < 0 {
combined = "minus " + combined
}
return combined, nil
}
func intMod(x, y int) int {
return int(math.Mod(float64(x), float64(y)))
}
func digitGroup2Text(group digitGroup, useAnd bool) (ret string) {
hundreds := group / 100
tensUnits := intMod(int(group), 100)
if hundreds != 0 {
ret += _smallNumbers[hundreds] + " hundred"
if tensUnits != 0 {
ret += separator(useAnd)
}
}
tens := tensUnits / 10
units := intMod(tensUnits, 10)
if tens >= 2 {
ret += _tens[tens]
if units != 0 {
ret += "-" + _smallNumbers[units]
}
} else if tensUnits != 0 {
ret += _smallNumbers[tensUnits]
}
return
}
// separator returns proper separator string between
// number groups.
func separator(useAnd bool) string {
if useAnd {
return " and "
}
return " "
}