2021-08-29 09:13:12 +00:00
|
|
|
package eval
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"strings"
|
|
|
|
|
2021-08-30 01:19:34 +00:00
|
|
|
"github.com/antonmedv/expr"
|
2021-08-29 09:13:12 +00:00
|
|
|
)
|
|
|
|
|
2021-08-29 10:22:14 +00:00
|
|
|
// EvaluateExpression evaulates a simple math expression string to a float64
|
|
|
|
func EvaluateExpressionToFloat64(input string) (float64, error) {
|
|
|
|
input = strings.TrimSpace(input) // remove trailing \0s
|
|
|
|
if input == "" {
|
2021-08-29 09:13:12 +00:00
|
|
|
return 0, nil
|
|
|
|
}
|
2021-08-30 01:19:34 +00:00
|
|
|
result, err := expr.Eval(input, nil)
|
2021-08-29 09:13:12 +00:00
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
f64, ok := result.(float64)
|
|
|
|
if !ok {
|
2021-08-30 01:19:34 +00:00
|
|
|
ival, ok := result.(int)
|
|
|
|
if !ok {
|
|
|
|
return 0, errors.New("could not type assert float64")
|
|
|
|
}
|
|
|
|
f64 = float64(ival)
|
2021-08-29 09:13:12 +00:00
|
|
|
}
|
|
|
|
return f64, nil
|
|
|
|
}
|