Handle commas in bytes parsing.
Fixes #42
diff --git a/bigbytes.go b/bigbytes.go
index 67ea5c8..d4fb371 100644
--- a/bigbytes.go
+++ b/bigbytes.go
@@ -138,15 +138,24 @@
// ParseBigBytes("42mib") -> 44040192, nil
func ParseBigBytes(s string) (*big.Int, error) {
lastDigit := 0
+ hasComma := false
for _, r := range s {
- if !(unicode.IsDigit(r) || r == '.') {
+ if !(unicode.IsDigit(r) || r == '.' || r == ',') {
break
}
+ if r == ',' {
+ hasComma = true
+ }
lastDigit++
}
+ num := s[:lastDigit]
+ if hasComma {
+ num = strings.Replace(num, ",", "", -1)
+ }
+
val := &big.Rat{}
- _, err := fmt.Sscanf(s[:lastDigit], "%f", val)
+ _, err := fmt.Sscanf(num, "%f", val)
if err != nil {
return nil, err
}
diff --git a/bigbytes_test.go b/bigbytes_test.go
index 88eed45..236ad08 100644
--- a/bigbytes_test.go
+++ b/bigbytes_test.go
@@ -40,6 +40,7 @@
{"42.5Mi", 44564480},
{"42.5 M", 42500000},
{"42.5 Mi", 44564480},
+ {"1,005.03 MB", 1005030000},
// Large testing, breaks when too much larger than
// this.
{"12.5 EB", uint64(12.5 * float64(EByte))},
diff --git a/bytes.go b/bytes.go
index dacbb9c..190ab65 100644
--- a/bytes.go
+++ b/bytes.go
@@ -109,14 +109,23 @@
// ParseBytes("42mib") -> 44040192, nil
func ParseBytes(s string) (uint64, error) {
lastDigit := 0
+ hasComma := false
for _, r := range s {
- if !(unicode.IsDigit(r) || r == '.') {
+ if !(unicode.IsDigit(r) || r == '.' || r == ',') {
break
}
+ if r == ',' {
+ hasComma = true
+ }
lastDigit++
}
- f, err := strconv.ParseFloat(s[:lastDigit], 64)
+ num := s[:lastDigit]
+ if hasComma {
+ num = strings.Replace(num, ",", "", -1)
+ }
+
+ f, err := strconv.ParseFloat(num, 64)
if err != nil {
return 0, err
}
diff --git a/bytes_test.go b/bytes_test.go
index 99cad92..0bb811c 100644
--- a/bytes_test.go
+++ b/bytes_test.go
@@ -39,6 +39,8 @@
{"42.5Mi", 44564480},
{"42.5 M", 42500000},
{"42.5 Mi", 44564480},
+ // Bug #42
+ {"1,005.03 MB", 1005030000},
// Large testing, breaks when too much larger than
// this.
{"12.5 EB", uint64(12.5 * float64(EByte))},