-
Notifications
You must be signed in to change notification settings - Fork 79
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
浮点数相乘 #15
Labels
bug
Something isn't working
Comments
这种好像没有做处理 🧐 |
可以使用 https://github.com/shopspring/decimal 做处理 package main
import (
"fmt"
"github.com/dengsgo/math-engine/engine"
"github.com/shopspring/decimal"
)
func main() {
s := "0.7*360"
// call top level function
r, err := engine.ParseAndExec(s)
if err != nil {
fmt.Println(err)
}
p, err := decimal.NewFromString(fmt.Sprintf("%f", r))
if err != nil {
panic(err)
}
fmt.Println(p) //252
} 本来想用 decimal 处理浮点数精度的问题,但是发现会损失精度 // Top level function
// Analytical expression and execution
// err is not nil if an error occurs (including arithmetic runtime errors)
func ParseAndExec(s string) (r float64, err error) {
toks, err := Parse(s)
if err != nil {
return 0, err
}
ast := NewAST(toks, s)
if ast.Err != nil {
return 0, ast.Err
}
ar := ast.ParseExpression()
if ast.Err != nil {
return 0, ast.Err
}
defer func() {
if e := recover(); e != nil {
err = e.(error)
}
}()
res, err := decimal.NewFromString(fmt.Sprintf("%f", ExprASTResult(ar)))
if err != nil {
return 0, err
}
r, _ = res.Float64()
return r, err
} === RUN TestParseAndExecSimple FAIL |
应该是要你保留多少个小数吧?这个看起来是被四舍五入了 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
0.7*360=251.99999999999997
The text was updated successfully, but these errors were encountered: