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

时间:2010-09-30 17:19:44

标签: php

我有这个号码:

$double = '21.188624';

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

21,19

但我想要的是:

21,18

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

谢谢。

15 个答案:

答案 0 :(得分:29)

number_format将永远这样做,您唯一的解决方案是为它提供不同的东西:

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

或者:

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

答案 1 :(得分:8)

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

这个功能怎么样?

function numberFormatPrecision($number, $precision = 2, $separator = '.')
{
    $numberParts = explode($separator, $number);
    $response = $numberParts[0];
    if(count($numberParts)>1){
        $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

// 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

// 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

答案 2 :(得分:7)

floor($double*100)/100

答案 3 :(得分:3)

我使用这个功能:

function cutNum($num, $precision = 2) {
    return floor($num) . substr(str_replace(floor($num), '', $num), 0, $precision + 1);
}

用法示例:

cutNum(5)          //returns 5 
cutNum(5.6789)     //returns 5.67 (default precision is two decimals)
cutNum(5.6789, 3)  //returns 5.678
cutNum(5.6789, 10) //returns 5.6789
cutNum(5.6789, 0)  //returns 5. (!don't use with zero as second argument: use floor instead!)

解释:这里你有相同的功能,只是为了帮助理解它的行为更加详细:

function cutNum($num, $precision = 2) {
    $integerPart = floor($num);
    $decimalPart = str_replace($integerPart, '', $num);
    $trimmedDecimal = substr($decimalPart, 0, $precision + 1);
    return $integerPart . $trimmedDecimal;
}

答案 4 :(得分:3)

使用PHP本机函数bcdiv

function numberFormat($number, $decimals = 2, $sep = ".", $k = ","){
    $number = bcdiv($number, 1, $decimals); // Truncate decimals without rounding
    return number_format($number, $decimals, $sep, $k); // Format the number
}

有关详细信息,请参阅this answer

答案 5 :(得分:2)

 **Number without round**        

   $double = '21.188624';
   echo intval($double).'.'.substr(end(explode('.',$double)),0,2);

**Output** 21.18

答案 6 :(得分:1)

$double = '21.188624';

$teX = explode('.', $double);

if(isset($teX[1])){
    $de = substr($teX[1], 0, 2);
    $final = $teX[0].'.'.$de;
    $final = (float) $final;
}else{
    $final = $double;   
}

最终将是21.18

答案 7 :(得分:1)

函数(仅精度):

function numberPrecision($number, $decimals = 0)
{
    $negation = ($number < 0) ? (-1) : 1;
    $coefficient = pow(10, $decimals);
    return $negation * floor((string)(abs($number) * $coefficient)) / $coefficient;
}

示例:

numberPrecision(2557.9999, 2);     // returns 2557.99
numberPrecision(2557.9999, 10);    // returns 2557.9999
numberPrecision(2557.9999, 0);     // returns 2557
numberPrecision(2557.9999, -2);    // returns 2500
numberPrecision(2557.9999, -10);   // returns 0
numberPrecision(-2557.9999, 2);    // returns -2557.99
numberPrecision(-2557.9999, 10);   // returns -2557.9999
numberPrecision(-2557.9999, 0);    // returns -2557
numberPrecision(-2557.9999, -2);   // returns -2500
numberPrecision(-2557.9999, -10);  // returns 0

功能(完整功能):

function numberFormat($number, $decimals = 0, $decPoint = '.' , $thousandsSep = ',')
{
    $negation = ($number < 0) ? (-1) : 1;
    $coefficient = pow(10, $decimals);
    $number = $negation * floor((string)(abs($number) * $coefficient)) / $coefficient;
    return number_format($number, $decimals, $decPoint, $thousandsSep);
}

示例:

numberFormat(2557.9999, 2, ',', ' ');     // returns 2 557,99
numberFormat(2557.9999, 10, ',', ' ');    // returns 2 557,9999000000
numberFormat(2557.9999, 0, ',', ' ');     // returns 2 557
numberFormat(2557.9999, -2, ',', ' ');    // returns 2 500
numberFormat(2557.9999, -10, ',', ' ');   // returns 0
numberFormat(-2557.9999, 2, ',', ' ');    // returns -2 557,99
numberFormat(-2557.9999, 10, ',', ' ');   // returns -2 557,9999000000
numberFormat(-2557.9999, 0, ',', ' ');    // returns -2 557
numberFormat(-2557.9999, -2, ',', ' ');   // returns -2 500
numberFormat(-2557.9999, -10, ',', ' ');  // returns 0

答案 8 :(得分:0)

使用此功能:

function number_format_unlimited_precision($number,$decimal = '.')
{
   $broken_number = explode($decimal,$number);
   return number_format($broken_number[0]).$decimal.$broken_number[1]);
}

答案 9 :(得分:0)

$finalCommishParts = explode('.',$commission);
$commisshSuffix = (isset($finalCommishParts[1])?substr($finalCommishParts[1],0,2):'00');
$finalCommish = $finalCommishParts[0].'.'.$commisshSuffix;

答案 10 :(得分:0)

public function numberFormatPrecision( $number, $separator = '.', $format = 2 ){

    $response = '';
    $brokenNumber = explode( $separator, $number );
    $response = $brokenNumber[0] . $separator;
    $brokenBackNumber = str_split($brokenNumber[1]);

    if( $format < count($brokenBackNumber) ){

        for( $i = 1; $i <= $format; $i++ )
            $response .= $brokenBackNumber[$i];
    }

    return $response;
}

答案 11 :(得分:0)

如果您不关心小数点后面的内容,可以将float转换为int以避免舍入:

$float = 2.8;
echo (int) $float; // outputs '2'

答案 12 :(得分:0)

爆炸(构建数组)的更快方法是使用这样的字符串命令:

$number = ABC.EDFG;
$precision = substr($number, strpos($number, '.'), 3); // 3 because . plus 2 precision  
$new_number = substr($number, 0, strpos($number, '.')).$precision;

在这种情况下,结果为ABC.ED,因为2精度 如果您想提高精度,只需将3更改为4或将X更改为X-1精度

欢呼

答案 13 :(得分:0)

Javascript 版本

function numberFormat($number, $decimals = 0, $decPoint = '.' , $thousandsSep = ',')
{
    return number_format((Math.floor($number * 100) / 100).toFixed($decimals), $decimals, $decPoint, $thousandsSep );
}
 // https://locutus.io/php/strings/number_format/
function number_format(number, decimals, decPoint, thousandsSep) {
    if(decimals === 'undefined') decimals = 2;

    number = (number + '').replace(/[^0-9+\-Ee.]/g, '')
  const n = !isFinite(+number) ? 0 : +number
  const prec = !isFinite(+decimals) ? 0 : Math.abs(decimals)
  const sep = (typeof thousandsSep === 'undefined') ? ',' : thousandsSep
  const dec = (typeof decPoint === 'undefined') ? '.' : decPoint
  let s = ''
  const toFixedFix = function (n, prec) {
    if (('' + n).indexOf('e') === -1) {
      return +(Math.round(n + 'e+' + prec) + 'e-' + prec)
    } else {
      const arr = ('' + n).split('e')
      let sig = ''
      if (+arr[1] + prec > 0) {
        sig = '+'
      }
      return (+(Math.round(+arr[0] + 'e' + sig + (+arr[1] + prec)) + 'e-' + prec)).toFixed(prec)
    }
  }
  // @todo: for IE parseFloat(0.55).toFixed(0) = 0;
  s = (prec ? toFixedFix(n, prec).toString() : '' + Math.round(n)).split('.')
  if (s[0].length > 3) {
    s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep)
  }
  if ((s[1] || '').length < prec) {
    s[1] = s[1] || ''
    s[1] += new Array(prec - s[1].length + 1).join('0')
  }
  return s.join(dec)
}

答案 14 :(得分:-1)

如果您的float值较小,则可以通过此方式使用number_format

$number = 21.23;

echo number_format($number, 2, '.', ',') ); // 21.23

如果您有长十进制数字,那么它也会以这种方式格式化数字

$number = 201541.23;

echo number_format($number, 2, '.', ',') ); // 201,541.23