cake-order-tracker/models/price.go
2026-06-15 15:50:17 +02:00

44 lines
845 B
Go

package models
import (
"fmt"
"log"
"strconv"
"strings"
)
type Price int
func (in Price) String() string {
if in%100 == 0 {
return strconv.Itoa(int(in) / 100)
} else {
price := strconv.Itoa(int(in))
i := len(price) - 2
price = price[:i] + "." + price[i:]
return price
}
}
func ParsePrice(in string) (Price, error) {
log.Println(in)
in = strings.ReplaceAll(in, ",", ".")
log.Println(in)
if !strings.Contains(in, ".") {
price, err := strconv.Atoi(in)
return Price(price) * 100, err
}
before, after, _ := strings.Cut(in, ".")
if len(after) > 2 {
return 0, fmt.Errorf("Wrong format, requires no more than 2 decimal places after the separator")
}
price, err := strconv.Atoi(before + after)
if len(after) < 2 {
price *= 10
}
if len(after) < 1 {
price *= 10
}
log.Println(price)
return Price(price), err
}