Skip to content

Instantly share code, notes, and snippets.

@knadh
Created June 12, 2022 08:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save knadh/1e09fd40bcab434194bedbb7aae33ad3 to your computer and use it in GitHub Desktop.
Save knadh/1e09fd40bcab434194bedbb7aae33ad3 to your computer and use it in GitHub Desktop.
Simple algorithm for converting numbers to English words (Golang)
package main
import (
"fmt"
)
var (
ones = []string{
"zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine",
"ten", "eleven", "twelve", "thirteen", "fourteen",
"fifteen", "sixteen", "seventeen", "eighteen", "nineteen",
}
tens = []string{
"", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety",
}
big = []string{
"", "thousand", "million", "billion", "trillion", "quadrillion", "quintillion",
}
)
func num2words(number int) string {
out := ""
if number == 0 {
return ones[0]
} else if number < 0 {
out += "minus"
number = number * -1
}
// Divide the number into groups of 3.
// eg: 9876543210 = [210 543 876 9] (should be read in reverse)
groups := []int{}
for {
if number < 1 {
break
}
groups = append(groups, number%1000)
number /= 1000
}
ln := len(groups) - 1
for i := ln; i >= 0; i-- {
n := groups[i]
if n == 0 {
continue
}
num := n
if v := num / 100; v != 0 {
out += " " + ones[v] + " hundred"
num = num % 100
}
if v := num / 10; num >= 20 && v != 0 {
out += " " + tens[v]
num = num % 10
}
if num > 0 {
out += " " + ones[num]
}
if i > 0 && i <= len(big) {
out += " " + big[i] + ","
}
}
return out[1:]
}
func main() {
fmt.Println(num2words(0))
fmt.Println(num2words(11))
fmt.Println(num2words(123))
fmt.Println(num2words(999))
fmt.Println(num2words(123999))
fmt.Println(num2words(987654321000000009))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment