【问题标题】:Round to 0.5 up and down and if 0 after dot docimal向上和向下舍入为 0.5,如果在点文档后为 0
【发布时间】:2019-07-16 09:03:12
【问题描述】:

嘿,我有以下问题, 我得到了收视率并获得了当时的平均水平,但我想追随:

1,2222222222222 = 1
1,2666666666666 = 1,5
2,3635345435435 = 2.5
2,567435 345345 = 2.5
3.5709 = 3
29,3003453450 = 29

我希望所有数字最接近 0.5,但是当它们没有小数时,不应该显示 3.0 或 4.0,只显示没有小数的数字。

目前我有这个代码:

function roundRating($rating) {
    return floor($rating * 2) / 2;
}

有人可以帮助我吗? 问候

【问题讨论】:

  • 3.57098 = 3.6 3 = 3 怎么了?为什么要将 29.3 舍入为 29 而不是 29.5?
  • 对不起这个例子是错误的

标签: php numbers rounding rating-system


【解决方案1】:

这是一个建议。请参阅 cmets 了解分步说明。

<?php

$float = 1.753242342;

// Modulo operator (%) does not return float remainder. Use fmod().
$remainder = fmod($float, 1);

/* Apply rounding logic here.
 * It isn't entirely clear to me what your intended behavior is.
 * Should 0.75 round up to 1 or down to 0.5?
 * I will leave this to you to figure out.
 */
$roundedRemainder = ($remainder >= 0.25)?0.5:0;

$int = $float - $remainder;
$result = $int + $roundedRemainder;
// If remainder is zero, cast to int to remove remainder.
if (fmod($result, 1) == 0)
        $result = (int)$result;

echo "Int: " . $int . "<br>";
echo "Remainder: " . $remainder . "<br>";
echo "Rounded remainder: " . $roundedRemainder . "<br>";
echo "Result: " . $result . "<br>";

输出:

Int: 1
Remainder: 0.753242342
Rounded remainder: 0.5
Result: 1.5

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-07
    • 1970-01-01
    • 2012-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多