diff --git a/dbms/src/Functions/FunctionsTiDBConversion.h b/dbms/src/Functions/FunctionsTiDBConversion.h index ec56e599b4c..d1b9710d758 100755 --- a/dbms/src/Functions/FunctionsTiDBConversion.h +++ b/dbms/src/Functions/FunctionsTiDBConversion.h @@ -951,12 +951,13 @@ struct TiDBConvertToDecimal } else if (v_scale > scale) { - const bool need_to_round = ((value < 0 ? -value : value) % scale_mul) >= (scale_mul / 2); + const bool neg = (value < 0); + const bool need_to_round = ((neg ? -value : value) % scale_mul) >= (scale_mul / 2); auto old_value = value; value /= scale_mul; if (need_to_round) { - if (value < 0) + if (neg) --value; else ++value; diff --git a/tests/fullstack-test/expr/cast_as_decimal.test b/tests/fullstack-test/expr/cast_as_decimal.test index aa85c592ec4..a375433b843 100644 --- a/tests/fullstack-test/expr/cast_as_decimal.test +++ b/tests/fullstack-test/expr/cast_as_decimal.test @@ -35,3 +35,28 @@ mysql> set @@tidb_isolation_read_engines='tiflash'; set @@tidb_enforce_mpp = 1; +------------------------------------+ | 20221010101010.123 | +------------------------------------+ + +mysql> drop table if exists test.t2; +mysql> create table test.t2(d decimal(11, 4)); +mysql> alter table test.t2 set tiflash replica 1; +mysql> insert into test.t2 values(-0.741); +mysql> alter table test.t2 set tiflash replica 1; +func> wait_table test t2 +mysql> set @@tidb_isolation_read_engines='tiflash'; set @@tidb_enforce_mpp = 1; SELECT cast(d as decimal) from test.t2; ++--------------------+ +| cast(d as decimal) | ++--------------------+ +| -1 | ++--------------------+ + +mysql> drop table if exists test.t2; +mysql> create table test.t2 (c1 int not null, c2 int not null, primary key(c1) CLUSTERED); +mysql> alter table test.t2 set tiflash replica 1; +mysql> insert into test.t2 (c1,c2) values (1486109909, -1113200806); +func> wait_table test t2 +mysql> set @@tidb_isolation_read_engines='tiflash'; set @@tidb_enforce_mpp = 1; select c2, c1, cast( (c2 / cast(c1 as signed)) as decimal) as c2 from test.t2; ++-------------+------------+------+ +| c2 | c1 | c2 | ++-------------+------------+------+ +| -1113200806 | 1486109909 | -1 | ++-------------+------------+------+