Jump to content

Recommended Posts

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

Link to comment
https://forums.phpfreaks.com/topic/197408-decimal-headaches-how-do-you-use-them/
Share on other sites

$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);

$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!

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.