【问题标题】:Comparing two strings in percent: if $a % of $b比较两个字符串的百分比:if $a % of $b
【发布时间】:2017-08-17 18:08:37
【问题描述】:

我需要在 PHP 中使用简短的 if/else 来比较两个字符串的百分比:

if ($sum['cur'] 70% of $sum['max']) {
    print ("Attention");
} else {
    print ("OK");
};

$sum['cur']$sum['max'] 是数字。例如,如果$sum['max']=100$sum['cur']=80,我想打印一个警告说 80% 正在使用中。

【问题讨论】:

  • 您只想要 80%,还是大于或等于 80%?

标签: php if-statement compare


【解决方案1】:

假设$sum['cur']$sum['max'] 是数字,那么它们是数字字符串还是实际数字都没有关系。当您尝试对它们进行数学运算或将它们与数字进行比较时,PHP 会自动将它们转换为必要的类型。

$percentage = 0.7;

if ($sum['cur'] / $sum['max'] >= $percentage) {
    print ("Attention");
} else {
    print ("OK");
};

如果您需要显示实际百分比,您可以预先计算而不是在条件中计算,以便在打印的消息中使用。由于您正在进行除法,因此结果中可能会出现一些长小数部分。您可以根据需要使用printf 对其进行格式化。

$threshold = 70;

$percentage = $sum['cur'] / $sum['max'] * 100;

if ($percentage >= $threshold) {
    printf("Attention: %d%% percent are in use", $percentage);
} else {
    echo "OK";
};

【讨论】:

    猜你喜欢
    • 2012-04-07
    • 2011-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多