# 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 ?
###### Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Commented:
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

Experts Exchange Solution brought to you by

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Commented:
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
Author 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
###### It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
MySQL Server

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.