How to make number_format() not to round numbers up

Viewed 70958

I have this number:

$double = '21.188624';

After using number_format($double, 2, ',', ' ') I get:

21,19

But what I want is:

21,18

Any ideea how can I make this work?

Thank you.

16 Answers

I know that this an old question, but it still actual :) .

How about this function?

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;
}

Usage:

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

Function (only precision):

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

Examples:

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 (full functionality):

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

Examples:

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
$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;   
}

final will be 21.18

In case you need 2 fixed decimal places, you can try this!

@Dima's solution is working for me, but it prints "19.90" as "19.9" so I made some changes as follows:

<?php 
function numberPrecision($number, $decimals = 0)
    {
        $negation = ($number < 0) ? (-1) : 1;
        $coefficient = 10 ** $decimals;
        $result = $negation * floor((string)(abs($number) * $coefficient)) / $coefficient;
        $arr = explode(".", $result);
        $num = $arr[0];
        if(empty($arr[1]))
            $num .= ".00";
        else if(strlen($arr[1]) == 1)
            $num .= "." . $arr[1] . "0";
        else
            $num .= ".". $arr[1];
        return $num;
    }
    echo numberPrecision(19.90,2); // 19.90

So, what I did is, I just break the result into two parts with explode function. and convert the result into a string with concatenation!

The faster way as exploding(building arrays) is to do it with string commands like this:

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

The result ist ABC.ED in this case because of 2 precision If you want more precision just change the 3 to 4 or X to have X-1 precision

Cheers

Javascript Version

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)
}
Related