Skip to content
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

expression: fix precision when casting float to string (#9137) #9227

Merged
merged 1 commit into from
Jan 31, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions expression/builtin_cast.go
Original file line number Diff line number Diff line change
Expand Up @@ -796,9 +796,20 @@ func (b *builtinCastRealAsStringSig) Clone() builtinFunc {
func (b *builtinCastRealAsStringSig) evalString(row chunk.Row) (res string, isNull bool, err error) {
val, isNull, err := b.args[0].EvalReal(b.ctx, row)
if isNull || err != nil {
return res, isNull, errors.Trace(err)
return res, isNull, err
}

bits := 64
if b.args[0].GetType().Tp == mysql.TypeFloat {
// b.args[0].EvalReal() casts the value from float32 to float64, for example:
// float32(208.867) is cast to float64(208.86700439)
// If we strconv.FormatFloat the value with 64bits, the result is incorrect!
bits = 32
}
res, err = types.ProduceStrWithSpecifiedTp(strconv.FormatFloat(val, 'f', -1, bits), b.tp, b.ctx.GetSessionVars().StmtCtx)
if err != nil {
return res, false, err
}
res, err = types.ProduceStrWithSpecifiedTp(strconv.FormatFloat(val, 'f', -1, 64), b.tp, b.ctx.GetSessionVars().StmtCtx)
return res, isNull, errors.Trace(err)
}

Expand Down
6 changes: 6 additions & 0 deletions expression/integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -572,6 +572,12 @@ func (s *testIntegrationSuite) TestStringBuiltin(c *C) {
result.Check(testkit.Rows("<nil>"))
result = tk.MustQuery("select concat(null, a, b) from t")
result.Check(testkit.Rows("<nil>"))
tk.MustExec("drop table if exists t")
// Fix issue 9123
tk.MustExec("create table t(a char(32) not null, b float default '0') engine=innodb default charset=utf8mb4")
tk.MustExec("insert into t value('0a6f9d012f98467f8e671e9870044528', 208.867)")
result = tk.MustQuery("select concat_ws( ',', b) from t where a = '0a6f9d012f98467f8e671e9870044528';")
result.Check(testkit.Rows("208.867"))

// for concat_ws
tk.MustExec("drop table if exists t")
Expand Down