Jump to content

Decimal headaches - how do you use them?!


BluMess

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!

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.