php – How to make number_format() not to round numbers up-ThrowExceptions

Exception or error:

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.

How to solve:

number_format will always do that, your only solution is to feed it something different:

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

Or:

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

Answer´╝Ü

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){
        $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

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

Answer´╝Ü

floor($double*100)/100

Answer´╝Ü

I use this function:

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

Usage examples:

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!)

Explanation: here you have the same function, just more verbose to help understanding its behaviour:

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

Answer´╝Ü

Use the PHP native function 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
}

See this answer for more details.

Answer´╝Ü

 **Number without round**        

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

**Output** 21.18

Answer´╝Ü

$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

Answer´╝Ü

Function (only precision):

function numberPrecision($number, $decimals = 0)
{
    $negation = ($number < 0) ? (-1) : 1;
    $coefficient = pow(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 = pow(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

Answer´╝Ü

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

Answer´╝Ü

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

Answer´╝Ü

In case you don’t care for what comes behind the decimal point, you can cast the float as an int to avoid rounding:

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

Answer´╝Ü

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

Answer´╝Ü

use this function:

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

Answer´╝Ü

In Case you have small float values you can use number_format function this way.

$number = 21.23;

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

In case you have you have long decimal number then also it will format number this way

$number = 201541.23;

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

Leave a Reply

Your email address will not be published. Required fields are marked *