如何使number_format()不向上舍入数字

php
2022-08-30 13:50:11

我有这个号码:

$double = '21.188624';

使用后,我得到:number_format($double, 2, ',', ' ')

21,19

但我想要的是:

21,18

任何想法我怎么能做到这一点?

谢谢。


答案 1

number_format总是会这样做,你唯一的解决方案是给它一些不同的东西:

$number = intval(($number*100))/100;

艺术

$number = floor(($number*100))/100;

答案 2

我知道这是一个古老的问题,但它仍然是实际:)。

这个功能怎么样?

function numberFormatPrecision($number, $precision = 2, $separator = '.')
{
    $numberParts = explode($separator, $number);
    $response = $numberParts[0];
    if (count($numberParts)>1 && $precision > 0) {
        $response .= $separator;
        $response .= substr($numberParts[1], 0, $precision);
    }
    return $response;
}

用法:

// numbers test
numberFormatPrecision(19, 2, '.'); // expected 19 return 19
numberFormatPrecision(19.1, 2, '.'); //expected 19.1 return 19.1
numberFormatPrecision(19.123456, 2, '.'); //expected 19.12 return 19.12
numberFormatPrecision(19.123456, 0, '.'); //expected 19 return 19

// negative numbers test
numberFormatPrecision(-19, 2, '.'); // expected -19 return -19
numberFormatPrecision(-19.1, 2, '.'); //expected -19.1 return -19.1
numberFormatPrecision(-19.123456, 2, '.'); //expected -19.12 return -19.12
numberFormatPrecision(-19.123456, 0, '.'); //expected -19 return -19

// precision test
numberFormatPrecision(-19.123456, 4, '.'); //expected -19.1234 return -19.1234

// separator test
numberFormatPrecision('-19,123456', 3, ','); //expected -19,123 return -19,123  -- comma separator

推荐