-
Notifications
You must be signed in to change notification settings - Fork 0
/
check.go
56 lines (43 loc) · 853 Bytes
/
check.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
package gobarcode
import (
"errors"
"math"
"strconv"
"strings"
)
func round(f int) int {
if f%10 == 0 {
return int(f)
}
f1 := float64(f) / 10
flooredF := math.Floor(f1 + 1.0)
return int(flooredF * 10)
}
func CheckEAN13(barcode string) (err error) {
barcode = strings.Trim(barcode, " ")
if len(barcode) != 13 {
return errors.New(ErrWrongLength)
}
if _, err := strconv.Atoi(barcode); err != nil {
return errors.New(ErrNotNumber)
}
even := false
sum := 0
for i := 0; i < 12; i++ {
digit := barcode[i : i+1]
intDigit, _ := strconv.Atoi(digit)
if even {
sum += intDigit * 3
} else {
sum += intDigit
}
even = !even
}
roundedSum := round(sum)
checkSum := roundedSum - sum
checkDigit, _ := strconv.Atoi(barcode[12:13])
if checkDigit != checkSum {
return errors.New(ErrWrongCheckSum)
}
return nil
}