Skip to content

Commit

Permalink
Do not divide then multiply as it may result in incorrect result (#37)
Browse files Browse the repository at this point in the history
For example, DurationValue("4236579305ms", ...) will return 4236579304, because
the result of diving 4236579305 by 1000 and then multiplying the result by 1000
will be 4.2365793049999995e+09, which when converted to int64 will result in
incorrect value.

Signed-off-by: Artem Fetishev <[email protected]>
  • Loading branch information
rtm0 authored Dec 3, 2024
1 parent 6559a88 commit e168a92
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 9 deletions.
18 changes: 9 additions & 9 deletions lexer.go
Original file line number Diff line number Diff line change
Expand Up @@ -575,25 +575,25 @@ func parseSingleDuration(s string, step int64) (float64, error) {
var mp float64
switch s[len(numPart):] {
case "ms":
mp = 1e-3
case "s":
mp = 1
case "s":
mp = 1000
case "m":
mp = 60
mp = 60 * 1000
case "h":
mp = 60 * 60
mp = 60 * 60 * 1000
case "d":
mp = 24 * 60 * 60
mp = 24 * 60 * 60 * 1000
case "w":
mp = 7 * 24 * 60 * 60
mp = 7 * 24 * 60 * 60 * 1000
case "y":
mp = 365 * 24 * 60 * 60
mp = 365 * 24 * 60 * 60 * 1000
case "i":
mp = float64(step) / 1e3
mp = float64(step)
default:
return 0, fmt.Errorf("invalid duration suffix in %q", s)
}
return mp * f * 1e3, nil
return mp * f, nil
}

// scanDuration scans duration, which must start with positive num.
Expand Down
1 change: 1 addition & 0 deletions lexer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -595,6 +595,7 @@ func TestDurationSuccess(t *testing.T) {
// Integer durations
f("123ms", 42, 123)
f("-123ms", 42, -123)
f("4236579305ms", 42, 4236579305)
f("123s", 42, 123*1000)
f("-123s", 42, -123*1000)
f("123m", 42, 123*60*1000)
Expand Down

0 comments on commit e168a92

Please sign in to comment.