Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 3307
  • Last Modified:

Sum() and decimals in MySQL

Hi

I need to produce a statement out of an accounting system I am making using MySQL.  I need to make a total of a certain field in a result set.  I would normally just use sum like so:

SELECT sum(amount) FROM tableName WHERE objID=1

However, the item I want to sum is made by doing a live percentage calculation within MySQL like so:

SELECT sum((amount * percentage / 100)) FROM tableName WHERE objID=1

My problem is that I want the sum to be done on figures rounded to two decimal places ie 1.5536 should be 1.55 so when doing the num the stray 0.0036 does not interfere with the final total.

Can I do this ?
0
rfila
Asked:
rfila
1 Solution
 
nicholassolutionsCommented:
ROUND(number, dec_places) will round number to the specified number of decimal places. So for example,

SELECT ROUND(10.554, 2);   ----> 10.55

so I think you could do something like:

SELECT sum((ROUND(amount,2) * ROUND(percentage,2) / 100));

Cheers,
Matt
0
 
minichickenCommented:
I am not too sure about the last part of your question, but shouldn't you only round after sum? Isn't it more accurate to round off at the final figure then rounding yoour calculating figures, it will lose accuracy.

SELECT ROUND(SUM(amount * percentage / 100),2) FROM tableName WHERE objID=1
0
 
rfilaAuthor Commented:
In the end I did this:

SUM(round((amount * percentage / 100), 2))

The sum is adding up the rounded off result for each row.  Therefore, when I print the result set with the rounded off figures if I add up the numbers they will come to the same amound as the result of this SQL request.  I was finding that they were slightly different sometimes because the fractions of pennys were cumulating.

Thanks!
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now