price fixes
This commit is contained in:
parent
2940f00142
commit
8d81940faf
4 changed files with 66 additions and 47 deletions
|
|
@ -2,6 +2,7 @@ package models
|
|||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
|
@ -20,14 +21,24 @@ func (in Price) String() string {
|
|||
}
|
||||
|
||||
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 exactly 2 decimal places after '.'")
|
||||
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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -31,6 +31,11 @@ func TestParsePrice(t *testing.T) {
|
|||
if err != nil || p != 199 {
|
||||
t.Fatal(s, p)
|
||||
}
|
||||
s = "1,99"
|
||||
p, err = ParsePrice(s)
|
||||
if err != nil || p != 199 {
|
||||
t.Fatal(s, p)
|
||||
}
|
||||
s = "1123"
|
||||
p, err = ParsePrice(s)
|
||||
if err != nil || p != 112300 {
|
||||
|
|
@ -41,15 +46,4 @@ func TestParsePrice(t *testing.T) {
|
|||
if err == nil {
|
||||
t.Fatal(s, "should error")
|
||||
}
|
||||
s = "1123.3"
|
||||
_, err = ParsePrice(s)
|
||||
if err == nil {
|
||||
t.Fatal(s, "should error")
|
||||
}
|
||||
|
||||
s = "1123,33"
|
||||
_, err = ParsePrice(s)
|
||||
if err == nil {
|
||||
t.Fatal(s, "should error")
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue