Skip to content

Commit

Permalink
fix cast to decimal wrong sign (#9300) (#9356)
Browse files Browse the repository at this point in the history
close #9301

Signed-off-by: guo-shaoge <[email protected]>

Co-authored-by: guo-shaoge <[email protected]>
Co-authored-by: ti-chi-bot[bot] <108142056+ti-chi-bot[bot]@users.noreply.github.com>
  • Loading branch information
3 people authored Sep 27, 2024
1 parent aa9c596 commit 08595f4
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
5 changes: 3 additions & 2 deletions dbms/src/Functions/FunctionsTiDBConversion.h
Original file line number Diff line number Diff line change
Expand Up @@ -1012,12 +1012,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;
Expand Down
25 changes: 25 additions & 0 deletions tests/fullstack-test/expr/cast_as_decimal.test
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
+-------------+------------+------+

0 comments on commit 08595f4

Please sign in to comment.