约束间隔之间的比例

i'm trying to make a small class in php that would be used to integrate a rating system and i'm stuck on a little probably simple problem. i want to show the rating between 0 and 5 but the votes can be in any interval like 1 to 10 or 1 to 12. for example if interval was of votes was 1-12 and total score/total votes would be 6 i want to actually display 2.5 i'm currently using this

$rating = number_format(round(($total_score/$total_votes)*2)/2,1);

so how can i make this to show values only 0-5 interval ?

$fromminrate = 1;
$frommaxrate = 12;
$tominrate = 0;
$tomaxrate = 5;
$rating = $tominrate + (
     ((($total_score/$total_votes)-$fromminrate)
     / ($frommaxrate-$fromminrate))
     * ($tomaxrate-$tominrate));

Use a simple percentage calculation like this:

<?php

$number_of_votes = 10; // real votes
$max_number_of_votes = 12; // vote range
$max_display_votes = 5; // display range

$perc = $max_display_votes * $number_of_votes / $max_number_of_votes;
$display = intval(round($perc)); // optional, round and convert to int

echo $display;

As a voting range - by its nature - starts at zero, you don't have to worry about the lower border and can simplify your calculations. ;)


Explanation:

The $number_of_votes(10) are related to $max_number_of_votes(12) as the value in question ($display) is related to $max_display_votes (5). In math:

$number_of_votes / $max_number_of_votes == $display / $max_display_votes;

or in the example:

10 / 12 = $display / 5;

You can transform this term by multiplying by 5:

10 * 5 / 12 = $display;

and thats my 'formula' ;)