PHP How do I round down to two decimal places?

假如想象 提交于 2019-11-26 03:40:47

问题


I need to round down a decimal in PHP to two decimal places so that:

49.955

becomes...

49.95

I have tried number_format, but this just rounds the value to 49.96. I cannot use substr because the number may be smaller (such as 7.950). I\'ve been unable to find an answer to this so far.

Any help much appreciated.


回答1:


This can work: floor($number * 100) / 100




回答2:


Here is a nice function that does the trick without using string functions:

<?php
function floorp($val, $precision)
{
    $mult = pow(10, $precision); // Can be cached in lookup table        
    return floor($val * $mult) / $mult;
}

print floorp(49.955, 2);
?>

An other option is to subtract a fraction before rounding:

function floorp($val, $precision)
{
    $half = 0.5 / pow(10, $precision); // Can be cached in a lookup table
    return round($val - $half, $precision);
}



回答3:


Unfortunately, none of the previous answers (including the accepted one) works for all possible inputs.

1) sprintf('%1.'.$precision.'f', $val)

Fails with a precision of 2 : 14.239 should return 14.23 (but in this case returns 14.24).

2) floatval(substr($val, 0, strpos($val, '.') + $precision + 1))

Fails with a precision of 0 : 14 should return 14 (but in this case returns 1)

3) substr($val, 0, strrpos($val, '.', 0) + (1 + $precision))

Fails with a precision of 0 : -1 should return -1 (but in this case returns '-')

4) floor($val * pow(10, $precision)) / pow(10, $precision)

Although I used this one extensively, I recently discovered a flaw in it ; it fails for some values too. With a precision of 2 : 2.05 should return 2.05 (but in this case returns 2.04 !!)

So far the only way to pass all my tests is unfortunately to use string manipulation. My solution based on rationalboss one, is :

function floorDec($val, $precision = 2) {
    if ($precision < 0) { $precision = 0; }
    $numPointPosition = intval(strpos($val, '.'));
    if ($numPointPosition === 0) { //$val is an integer
        return $val;
    }
    return floatval(substr($val, 0, $numPointPosition + $precision + 1));
}

This function works with positive and negative numbers, as well as any precision needed.




回答4:


Multiply your input by 100, floor() it, then divide the result by 100.




回答5:


Try the round() function

Like this: round($num, 2, PHP_ROUND_HALF_DOWN);




回答6:


function roundDown($decimal, $precision)
{
    $sign = $decimal > 0 ? 1 : -1;
    $base = pow(10, $precision);
    return floor(abs($decimal) * $base) / $base * $sign;
}

// Examples
roundDown(49.955, 2);           // output: 49.95
roundDown(-3.14159, 4);         // output: -3.1415
roundDown(1000.000000019, 8);   // output: 1000.00000001

This function works with positive and negative decimals at any precision.

Code example here: http://codepad.org/1jzXjE5L




回答7:


You can use bcdiv PHP function.

bcdiv(49.955, 1, 2)



回答8:


I think there is quite a simple way to achieve this:

$rounded = bcdiv($val, 1, $precision);

Here is a working example. You need BCMath installed but I think it's normally bundled with a PHP installation. :) Here is the documentation.




回答9:


function floorToPrecision($val, $precision = 2) {
        return floor(round($val * pow(10, $precision), $precision)) / pow(10, $precision);
    }



回答10:


Use formatted output

sprintf("%1.2f",49.955) //49.95

DEMO




回答11:


You can use:

$num = 49.9555;
echo substr($num, 0, strpos($num, '.') + 3);



回答12:


An alternative solution using regex which should work for all positive or negative numbers, whole or with decimals:

if (preg_match('/^-?(\d+\.?\d{1,2})\d*$/', $originalValue, $matches)){
    $roundedValue = $matches[1];
} else {
    throw new \Exception('Cannot round down properly '.$originalValue.' to two decimal places');
}



回答13:


Based on @huysentruitw and @Alex answer, I came up with following function that should do the trick.

It pass all tests given in Alex's answer (as why this is not possible) and build upon huysentruitw's answer.

function trim_number($number, $decimalPlaces) {
    $delta = (0 <=> $number) * (0.5 / pow(10, $decimalPlaces));
    $result = round($number + $delta, $decimalPlaces);
    return $result ?: 0; // get rid of negative zero
}

The key is to add or subtract delta based on original number sign, to support trimming also negative numbers. Last thing is to get rid of negative zeros (-0) as that can be unwanted behaviour.

Link to "test" playground.

EDIT: bcdiv seems to be the way to go.

// round afterwards to cast 0.00 to 0
// set $divider to 1 when no division is required
round(bcdiv($number, $divider, $decimalPlaces), $decimalPlaces);



回答14:


For anyone in need, I've used a little trick to overcome math functions malfunctioning, like for example floor or intval(9.7*100)=969 weird.

function floor_at_decimals($amount, $precision = 2)
{
    $precise = pow(10, $precision);
    return floor(($amount * $precise) + 0.1) / $precise;
}

So adding little amount (that will be floored anyways) fixes the issue somehow.




回答15:


sprintf("%1.2f",49.955) //49.95

if you need to truncate decimals without rounding - this is not suitable, because it will work correctly until 49.955 at the end, if number is more eg 49.957 it will round to 49.96
It seems for me that Lght`s answer with floor is most universal.




回答16:


What about this?

$value = 49.955;

echo intval( $value * 100 ) / 100;

Here is a demo




回答17:


Did you try round($val,2) ?

More information about the round() function



来源:https://stackoverflow.com/questions/12277945/php-how-do-i-round-down-to-two-decimal-places

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!