33 lines
655 B
Go
33 lines
655 B
Go
package models
|
|
|
|
import (
|
|
"fmt"
|
|
"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) {
|
|
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 exactly 2 decimal places after '.'")
|
|
}
|
|
price, err := strconv.Atoi(before + after)
|
|
return Price(price), err
|
|
}
|