如何将百分比(例如25%)简化为一个简单的语句(例如四分之一)



我需要将一个数字和总数数组转换为一个简单的语句。

例如,我如何通过PHP以编程方式将以下内容转换为简单的语句,如1 out of 101 out of 100,甚至四舍五入(如2 out of 100表示9000400000)。

生成样本阵列:

$arr = array();
for ($i=0; $i < 100; $i++) {
    $n = mt_rand(1,1000);
    $t = mt_rand(10,100000);
    if ($n > $t) continue; // skip!
    $arr[] = array($n,$t);
}
/*
// Generates pairs like:
// Array
// (
//     [0]  => Array ( [0] => 55  [1] => 8774  )
//     [1]  => Array ( [0] => 814 [1] => 11174 )
//     [2]  => Array ( [0] => 255 [1] => 32168 )
//     ...
//     [99] => Array ( [0] => 851 [1] => 24231 )
// )
*/

运行一个函数并打印简化的结果:

foreach ($arr as $a) {
    echo $a[0] . '/' . $a[1] . ' ==> ' . simplifyRatio($a[0],$a[1]) . "rn";
}

你能为我指出如何实现这一目标的正确方向吗?

这是我正在处理的一个函数的开始,但解决方案正在逃离我

function simplifyRatio($n,$t) {
    $p = $n/$t;
    if ($p > 0.09) return round($n) . ' out of ' . round($t);
    if ($p > 0.009) return round($n) . ' out of ' . round($t);
}

理想情况下,分母应为:1,2,3...10,20,30...100,200,300...1000,2000,3000...10000,20000,30000...100000 (max)

假设总是一个百分比。在显示之前,您可能还想冲刺$outof

function convertPercent($iPercent)
{
  // Assume validation on $iPercent
  $outof = round(100 / $iPercent);
  return "1 out of $outof";
}

为了简单起见,我假设你可以在一个分数中得到你的百分比(即25%是25/100,0.7%=7/1000,等等)。

您可以使用欧几里得算法来找到分子和分母的GCD:http://en.wikipedia.org/wiki/Euclidean_algorithm

在php中,它看起来像这样:

function gcd ($int1, $int2) {
    $tmp = 0;
    while ($int1 > 0) {
        $tmp = $int1;
        $int1 = $int2 % $int1;
        $int2 = $tmp;
    }
    return $int2;
}

只要$int1和$int2是大于0的整数(您可能需要放入一些逻辑来确保这一点),这将起作用。如果你需要负数,就取绝对值。

知道GCD,就很容易弄清楚剩下的:

function reduce($numerator, $denominator) {
    $gcd = gcd($numerator, $denominator);
    echo ($numerator/$gcd) . " out of " . ($denominator/$gcd);
}
echo reduce(4, 8).'<br>'; // 1 out of 2
echo reduce(38, 897).'<br>'; // 38 out of 897
echo reduce(39, 26).'<br>'; // 3 out of 2

希望这能有所帮助!

我最终在模式1 out of ___上达成了近乎匹配的结果,如下所示:

function simplifyRatio($n,$t) {
    $r = $t/$n;
    return '1 out of ' . round($r);
}
// Examples:
$arr = array();
for ($i=0; $i < 100; $i++) {
    $n = mt_rand(1,1000);
    $t = mt_rand(10,100000);
    if ($n > $t) continue; // skip!
    $arr[] = array($n,$t);
}
foreach ($arr as $a) {
    echo $a[0] . '/' . $a[1] . ' ==> ' . simplifyRatio($a[0],$a[1]) . "rn";
}

示例结果:

1000/24819 ==> 1 out of 25
309/50305 ==> 1 out of 163
488/99123 ==> 1 out of 203
322/47610 ==> 1 out of 148
183/54287 ==> 1 out of 297
752/67646 ==> 1 out of 90
240/68854 ==> 1 out of 287
301/81345 ==> 1 out of 270
611/16404 ==> 1 out of 27
522/62992 ==> 1 out of 121

CodePad:http://codepad.org/wu6iOdDq

起初,我希望最终得到四舍五入的分母(10,20…100200…10002000等),但我不确定如何做好这件事。我会很高兴地给出一个能清除上述分母的答案。

最新更新