summaryrefslogtreecommitdiff
path: root/crawler/convert_price.go
blob: d9725a0366305ab283bfca9e526998ec07f104c7 (plain)
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
package main

import (
	"errors"
	"strconv"
	"strings"
)

func convert_price(price string) (int, error) {
	if "" == price {
		return 0, errors.New("Empty string")
	}

	multiply_by_10 := false
	multiply_by_100 := true

	price = strings.TrimSpace(price)

	price = strings.TrimPrefix(price, "€")
	price = strings.TrimSpace(price)

	price = strings.TrimSuffix(price, "€")
	price = strings.TrimSpace(price)

	price = strings.TrimSuffix(strings.ToLower(price), "eur")
	price = strings.TrimSpace(price)

	price = strings.TrimSuffix(strings.ToLower(price), "euro")
	price = strings.TrimSpace(price)

	if len(price) < 2 {
		price = "00" + price
	} else if len(price) < 3 {
		price = "0" + price
	}

	c := string(price[len(price)-2:])
	c = string(c[0:1])

	/*
		Extracts the second last char and checks if it's a "." or a ",".
	*/
	if "," == c {
		if strings.Count(price, ",") > 1 {
			return 0, errors.New("Invalid format")
		}

		multiply_by_10 = true
		multiply_by_100 = false

	} else if "." == c {
		if strings.Count(price, ".") > 1 {
			return 0, errors.New("Invalid format")
		}

		multiply_by_10 = true
		multiply_by_100 = false

	}

	c = string(price[len(price)-3:])
	c = string(c[0:1])

	/*
		Extracts the third last char and checks if it's a "." or a ",".
	*/
	if "," == c {
		if strings.Count(price, ",") > 1 {
			return 0, errors.New("Invalid format")
		}

		multiply_by_10 = false
		multiply_by_100 = false

	} else if "." == c {
		if strings.Count(price, ".") > 1 {
			return 0, errors.New("Invalid format")
		}

		multiply_by_10 = false
		multiply_by_100 = false

	}

	price = strings.Replace(price, ",", "", -1)
	price = strings.Replace(price, ".", "", -1)

	/*
		Casts the price to integer in cents (not euro!).
	*/
	price_int, err := strconv.Atoi(price)
	if err != nil {
		return 0, err
	}

	if multiply_by_10 {
		price_int = price_int * 10
	} else if multiply_by_100 {
		price_int = price_int * 100
	}

	return price_int, nil
}