You can use the format()
function:
select format(col1 - col2, length(substring_index(col1, '.', -1)))
If you don't like the commas on larger numbers:
select replace(format(col1 - col2, length(substring_index(col1, '.', -1))), ',', '')
Question
The following subtraction query returns too many digits after the decimal mark.
mysql> select AA, BB, AA - BB, AA - 23.057, 22.659 - 23.057 from table1 where TID = '1';
+----------+----------+---------------------+---------------------+-----------------+
| AA | BB | AA - BB | AA - 23.057 | 22.659 - 23.057 |
+----------+----------+---------------------+---------------------+-----------------+
| 22.659 | 23.057 | -0.3979999999999997 | -0.3979999999999997 | -0.398 |
+----------+----------+---------------------+---------------------+-----------------+
1 row in set (0.00 sec)
mysql>
I wish I could use a decimal fields, but the user wants to keep the precision he inserts at input time in the columns AA and BB, that's why VARCHAR is used for those column.
e.g.: 11.10 - 11.22 = - 0.02
11.20 - 11.10 = + 0.10
22.659 - 23.057 = -0.398
23.659 - 22.559 = 0.100
while 23.659 - 22.559 = 0.1 is wrong
Any help would greatly appreciate. Thanks
Solution
You can use the format()
function:
select format(col1 - col2, length(substring_index(col1, '.', -1)))
If you don't like the commas on larger numbers:
select replace(format(col1 - col2, length(substring_index(col1, '.', -1))), ',', '')