i have a MySQL table namely estimate_item which contains few columns that holds decimal values with fixed precisions. here is my table structure.
tableName : estimate_item

while retrieving the records using PHP, i do some basic calculations using MySQL’s function, the SQL query i use is this.
SELECT
COUNT(ei.item_id) as total_item,
SUM(ei.quantity) as total_quantity,
SUM(ei.number_of_carton) as total_carton,
SUM(ei.number_of_carton * ei.cbm_per_carton) as total_cbm,
SUM(ei.quantity * ei.cost) as total_cost,
SUM(ei.quantity * ei.rate) as total_rate,
e.commission_amount,
SUM(ei.quantity * ei.rate) + e.commission_amount as total_amount
FROM
ai_estimate e
LEFT JOIN
ai_estimate_item ei ON ei.estimate_id = e.id
WHERE
ei.estimate_id = ?
for example the above query returns the result.
+------------+----------------+--------------+-----------+------------+------------+-------------------+--------------+
| total_item | total_quantity | total_carton | total_cbm | total_cost | total_rate | commission_amount | total_amount |
+------------+----------------+--------------+-----------+------------+------------+-------------------+--------------+
| 2 | 120 | 807 | 1122.6440 | 2.7500 | 137.5000 | 1500.00 | 1637.5000 |
+------------+----------------+--------------+-----------+------------+------------+-------------------+--------------+
since the following columns contains 4 precision values total_cbm_total, total_cost, total_rate, total_amount, i want to round up the values of all four columns this way.
a) if value is 1122.6440 then round it to 1122.644
b) if value is 2.7500 then round it to 2.75
c) if value is 137.5000 then round it to 137.50
d) if value is 1200.0000 then round it to 1200.00
i.e i want the values to contain minimum of two precisions, which can go up to 3 or 4 precision depending upon the values.
is there any way i could do this directly in MySQL? or the PHP way?
thanks and regards.
If you do that in MySQL, my guess is that you’d need to overly complicate the query adding a CASE WHEN… END.
So I’d do that in PHP.
This employs a trick – first it calculates the representation with two and three digits, then checks whether these are the same floating number. If they are, then the last digit of the three-digit version must be zero and the two-digit version is used instead.
To extend to 2, 3 or 4 digits, you could do that in a cycle:
or, since string functions are very likely to be faster than number_format: