Skip to content

Commit

Permalink
expression: fix precision when casting float to string (#9137) (#9227)
Browse files Browse the repository at this point in the history
  • Loading branch information
tiancaiamao authored and zz-jason committed Jan 31, 2019
1 parent 82f8d55 commit d97b8ed
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
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

0 comments on commit d97b8ed

Please sign in to comment.