Skip to content

Commit

Permalink
Improved flexint.go
Browse files Browse the repository at this point in the history
  • Loading branch information
arturogonzalezm committed Jul 29, 2024
1 parent 01e481b commit bc5c59f
Showing 1 changed file with 13 additions and 2 deletions.
15 changes: 13 additions & 2 deletions pkg/flexint/flexint.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ func (i *Int64) UnmarshalJSON(data []byte) error {
// Try to unmarshal as a float64 and then convert
var floatVal float64
if err := json.Unmarshal(data, &floatVal); err == nil {
roundedVal := math.RoundToEven(floatVal)
roundedVal := roundHalfToEven(floatVal)
if roundedVal > float64(math.MaxInt64) {
*i = Int64(math.MaxInt64)
} else if roundedVal < float64(math.MinInt64) {
Expand All @@ -43,7 +43,7 @@ func (i *Int64) UnmarshalJSON(data []byte) error {
*i = Int64(intVal)
return nil
} else if floatVal, err := strconv.ParseFloat(strVal, 64); err == nil {
roundedVal := math.RoundToEven(floatVal)
roundedVal := roundHalfToEven(floatVal)
if roundedVal > float64(math.MaxInt64) {
*i = Int64(math.MaxInt64)
} else if roundedVal < float64(math.MinInt64) {
Expand All @@ -57,3 +57,14 @@ func (i *Int64) UnmarshalJSON(data []byte) error {

return errors.New("invalid value for Int64")
}

func roundHalfToEven(val float64) float64 {
if val == float64(int64(val)) {
return val
}
floor := math.Floor(val)
if val-floor > 0.5 || (val-floor == 0.5 && int64(floor)%2 != 0) {
return floor + 1
}
return floor
}

0 comments on commit bc5c59f

Please sign in to comment.