BluMess Posted April 2, 2010 Share Posted April 2, 2010 Hi all, Here is an extremely novice problem, yet the amount of times I have searched for an answer I haven't found anything, so I'm hoping someone could help me out Basically I have a column "rating" which I want to store a number between 1 and 10, but with say 2 or 3 decimal places e.g. 6.236 So I thought this would work for mysql: `rating` dec(4,2) NOT NULL DEFAULT '0', but it seems to just limit the number to being "4.00" this is my php part: echo "total value: ".$rating['total_value']."<br>"; echo "total votes: ".$rating['total_votes']."<br>"; $current_rating = $rating['total_value']/$rating['total_votes']; $printf_curr_rating = printf("%04.2f", $current_rating); echo "Current rating: ".$current_rating."<br>"; $add_curr_rating = mysql_query("UPDATE media SET rating='".$printf_curr_rating."' WHERE id=".$new_id."") or die("Update rating error: ".mysql_error()); if($add_curr_rating){ echo "-Updated rating for the media id to:".$printf_curr_rating."<br>"; } This is what my script returns: total value: 154 total votes: 20 7.70Current rating: 7.7 -Updated rating for the media id to:4 And, likewise in the db, it says the decimal is 4.00 What is going on? Thank you ~Chris Quote Link to comment https://forums.phpfreaks.com/topic/197408-decimal-headaches-how-do-you-use-them/ Share on other sites More sharing options...
DavidAM Posted April 3, 2010 Share Posted April 3, 2010 $printf_curr_rating = printf("%04.2f", $current_rating); is causing the problem. It PRINTS the value (7.70) and RETURNS the length (4). You want to use sprintf() to assign the formatted number to string. $printf_curr_rating = sprintf("%04.2f", $current_rating); Quote Link to comment https://forums.phpfreaks.com/topic/197408-decimal-headaches-how-do-you-use-them/#findComment-1036236 Share on other sites More sharing options...
BluMess Posted April 3, 2010 Author Share Posted April 3, 2010 $printf_curr_rating = printf("%04.2f", $current_rating); is causing the problem. It PRINTS the value (7.70) and RETURNS the length (4). You want to use sprintf() to assign the formatted number to string. $printf_curr_rating = sprintf("%04.2f", $current_rating); Thanks, works perfectly! Quote Link to comment https://forums.phpfreaks.com/topic/197408-decimal-headaches-how-do-you-use-them/#findComment-1036390 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.