issue in decimal places

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
itsmani1
Forum Regular
Posts: 791
Joined: Mon Sep 29, 2003 2:26 am
Location: Islamabad Pakistan
Contact:

issue in decimal places

Post by itsmani1 »

Code: Select all

mysql_query("SELECT avg( vote ) as average, sum( vote ) as total, count( vote ) as total_v FROM story_vote where sid = $poetryid") or die(mysql_error());
in result it shows me 3.00000 and i want it to show 3.0
User avatar
andym01480
Forum Contributor
Posts: 390
Joined: Wed Apr 19, 2006 5:01 pm

Post by andym01480 »

Use the ROUND function in the query

The following found using google

Code: Select all

ROUND(x) and ROUND(x,y)
Returns the value of x rounded to the nearest integer. ROUND can also accept an additional argument y that will round x to y decimal places.

select ROUND(14.492);
+---------------+
| ROUND(14.492) |
+---------------+
|            14 |
+---------------+
1 row in set (0.00 sec)

select ROUND(4.5002);
+---------------+
| ROUND(4.5002) |
+---------------+
|             5 |
+---------------+
1 row in set (0.00 sec)

select ROUND(-12.773);
+----------------+
| ROUND(-12.773) |
+----------------+
|            -13 |
+----------------+
1 row in set (0.00 sec)

select ROUND(7.235651, 3);
+--------------------+
| ROUND(7.235651, 3) |
+--------------------+
|              7.236 |
+--------------------+
1 row in set (0.00 sec)
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Post by Christopher »

You can use the MySQL TRUNCATE(value, ndigits) function in the query or use the PHP number_format() function on the returned values.
(#10850)
User avatar
andym01480
Forum Contributor
Posts: 390
Joined: Wed Apr 19, 2006 5:01 pm

Post by andym01480 »

Mmmm learnt something there. Is that better than Round or have I got it wrong again!
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Post by onion2k »

Actually you want to use ROUND() .. but make sure you use 2 arguments .. eg ROUND(columnname, 1). If your number is 1.678, and you use TRUNCATE(1.678,1) you'll get 1.6 .. if you use ROUND(1.678,1) you'll get 1.7. TRUNCATE() just chops off the rest of the number, it's very unlikely that's what you actually want.

If you're outputting the number to the screen rather than using it mathematically, consider using FORMAT() instead.
Post Reply