Page 1 of 1

PHP Rounding Up Issue

Posted: Mon Nov 09, 2009 7:21 am
by koolsamule
Hi Chaps,

I have an SQL query that calculates a word count multiplied by a fixed figure:

Code: Select all

...$pricegross = ($row_rsInvPending['projanalysis_total']*$row_rsInvPending['costbase']);...
Then use a bit of php code to round up the figure to 2 decimal places....

Code: Select all

<?php echo number_format($pricegross, 2, '.', ''); ?>

I then total up $pricegross for all records:

Code: Select all

.....SELECT SUM(projanalysis_total) as total_pricegross...
If I have two records:
($pricegross) 1. £2.295
($pricegross) 2. £2.295
There are both displayed as £2.30, which is what I want

Then the total ($total_pricegross) shows up as £4.59, but what I want is: £4.60

Is this possible?....Hope this is clear?!

Re: PHP Rounding Up Issue

Posted: Mon Nov 09, 2009 8:39 am
by N1gel
Could you round to 1 decimal place and put a 0 on the end?

That would round to the nearest 10p like in your examples

Code: Select all

 
echo '£'.number_format(2.295,1, '.', '').'0';
echo '£'.number_format(4.59,1, '.', '').'0';
£2.30
£4.60

Re: PHP Rounding Up Issue

Posted: Mon Nov 09, 2009 8:59 am
by koolsamule
Yeah, that works, I'll have to see if this is going to be good enough for our company. . . .thanks!

Re: PHP Rounding Up Issue

Posted: Mon Nov 09, 2009 9:07 am
by N1gel
Ok.

But if your not happy with the String concatenation you could round it to the nearest 10 pence and then format it to two decimal places. (its gives the same result)

Code: Select all

echo '£'.number_format(round(2.295,1),2, '.', '');

Re: PHP Rounding Up Issue

Posted: Mon Nov 09, 2009 9:13 am
by papa
Check out ceil() or round() instead.

Re: PHP Rounding Up Issue

Posted: Mon Nov 09, 2009 9:22 am
by N1gel
I think you miss the point.

ceil() will round up to an integer which isn't what is asked for.

and round() has the same rounding function as number_format().

Re: PHP Rounding Up Issue

Posted: Mon Nov 09, 2009 9:22 am
by koolsamule
sweet, thanks chaps!

Re: PHP Rounding Up Issue

Posted: Mon Nov 09, 2009 9:34 am
by papa
N1gel wrote:I think you miss the point.

ceil() will round up to an integer which isn't what is asked for.

and round() has the same rounding function as number_format().
Round and number_format differs a bit, but I confess I read the original post a bit too fast.. :)

Re: PHP Rounding Up Issue

Posted: Mon Nov 09, 2009 2:39 pm
by McInfo
You can use ceil() if you shift the decimal first.

Code: Select all

$n = ceil($n * 100) / 100;
The entire operation can be done in SQL.

Code: Select all

SET @cost_per_word = 0.001;
 
SELECT ROUND(SUM(CEIL(`word_count` * @cost_per_word * 100) / 100), 2) FROM `table`;
# The outer ROUND() is to remove trailing zeros
Edit: This post was recovered from search engine cache.