上下舍入为0.5,小数点后为0

时间:2019-02-22 09:42:40

标签: php numbers rounding rating-system

嘿,我有以下问题, 我得到评分并具有当时的平均值,但我要鞠躬:

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

我希望所有数字都最接近.5,但是当它们没有小数时,则不应显示3.0或4.0,而应仅显示不带小数的数字。

此刻我有以下代码:

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

有人可以帮助我吗? 问候

1 个答案:

答案 0 :(得分:0)

这是一个建议。请查看评论以获取逐步说明。

import {getFoo} from './main'
let bar = getFoo() + "baz";

输出:

<?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>";