Validate Numbers With Luhn Checksum
The Luhn checksum doubles every second digit from the right, folds two-digit products, and accepts the number only when the total divides by ten.
Code
package main
import (
"fmt"
"strconv"
"strings"
)
// luhn: double every second digit from the right; subtract 9 when the doubled value exceeds 9
func luhnValid(number string) bool {
number = strings.ReplaceAll(number, " ", "")
if len(number) < 2 {
return false
}
sum := 0
double := false
for i := len(number) - 1; i >= 0; i-- {
digit, err := strconv.Atoi(string(number[i]))
if err != nil {
return false
}
if double {
digit *= 2
if digit > 9 {
digit -= 9
}
}
sum += digit
double = !double
}
return sum%10 == 0
}
func main() {
for _, number := range []string{"4539 1488 0343 6467", "4539 1488 0343 6468", "1234"} {
fmt.Println(number, "->", luhnValid(number))
}
}What the code does
What another module actually calls is the functions luhnValid and main — everything else is wiring.
The loop for i := len(number) - 1; i >= 0; i-- is the only repeated construct. Error handling is inline: 1 place test err != nil and branch immediately.
Watch out for
- Nothing sits in the dependency list; the runtime itself supplies it all.
Applying it
The primary signature, spelled out, is func luhnValid(number string) bool
The demo flow inside main is luhnValid — run the file to see it end to end.
Statements that matter most here
for _, number := range []string{"4539 1488 0343 6467", "4539 1488 0343 6468", "1234"} {
fmt.Println(number, "->", luhnValid(number))
}
if err != nil {
return false
}
return sum%10 == 0
Interactive Tools for This Topic
Luhn Checksum ValidatorValidate numeric identifiers with the Luhn algorithm and see the checksum sum and suggested final digit on failure.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.IMEI ValidatorValidate 15-digit IMEI numbers with the Luhn checksum, with a full digit-by-digit computation trace and TAC/SNR field breakdown.
FAQ
- How do you run Validate Numbers With Luhn Checksum?
- Run the file on its own; every call resolves against the standard surface it already imports.
Report a problem with this exampleOpens a pre-filled issue on GitHub.