PHP round half up doesn't work

php

1100 просмотра

3 ответа

I have this code

<?php echo round(0.572,2,PHP_ROUND_HALF_UP);?>

I want to round two decimals to half up, I expect a value as 0.58... but the above code print 0.57

How can I do this?

Автор: Funny Frontend Источник Размещён: 12.11.2019 09:14

Ответы (3)


1 плюс

Решение

if you expect 0,58 you don't have to use a "half round" but the ceil function

$v = 0.575;
echo ceil($v * 100) / 100; // show 0,58
Автор: mmm Размещён: 01.07.2015 06:21

1 плюс

The value 0.572 can not be rounded up to 0.58, because the third decimal, 2, is less than half (or 5). If you were doing round(0.575, 2, PHP_ROUND_HALF_UP) you would get 0.58. In this case 0.57 is the correct rounded value.

If you wish to always round up from the 3rd decimal, regardless of its value you could use ciel() instead, but it requires a little additional math. A simple function to demonstrate rounding up always would be...

function forceRoundUp($value, $decimals)
{
    $ord = pow(10, $decimals);
    return ceil($value * $ord) / $ord;
}

echo forceRoundUp(0.572, 2); // 0.58
echo forceRoundUp(0.57321, 4); // 0.5733
Автор: Sherif Размещён: 01.07.2015 06:17

0 плюса

function round_up($value, $places)
{
  $mult = pow(10, abs($places));
  return $places < 0 ?
  ceil($value / $mult) * $mult :
  ceil($value * $mult) / $mult;
}

echo round_up(0.572,2);

Hope this will work for you!!

Автор: Amol Bansode Размещён: 01.07.2015 06:24
Вопросы из категории :
32x32