I'm trying to achieve the same amount of precision (number of digits after decimal point) for results coming from a SELECT that does some equations.
- Is there any difference in terms of performance, good practice of use in case of achieving wanted precision between CAST() or ROUND() besides rounding by the last one? Is there any better alternative?
For the sake of simplicity values in all examples below are hardcoded, they may or may not come from table's columns
I'm using MySQL 8.
If you run example E1
:
-- E1
SELECT (41/99);
-- 0.4141
you'll get 4 digits after decimal point.
Is there any MySQL setting that can bring higher precision right out of the box so I don't need to use:
-- E2 SELECT ROUND((41/99), 20); -- 0.41414141400000000000
-- or
SELECT CAST((41/99) AS DECIMAL(21,20)); -- 0.41414141400000000000
How to get more decimal points precision from
E2
in case data used for calculation is int?
If you supply data with decimal point you get much higher precision:
-- E3
SELECT ROUND((41.0/99.0), 20);
-- 0.41414141414141414100
SELECT CAST((41.0/99.0) AS DECIMAL(21,20));
-- 0.41414141414141414100
It is important to me to avoid floating point datatypes due to their approximation of decimals. If the data be coming from table column the column will be decimal datatype. But data for calculations may be also hardcoded.