Mostrar un número a 2 decimales


¿Cuál es la forma correcta de redondear una cadena PHP a 2 decimales?

$number = "520"; // It's a string from a DB

$formatted_number = round_to_2dp($number);

echo $formatted_number;

La salida debe ser 520.00;

¿Cómo debería ser la definición de la función round_to_2dp()?

Author: Ivar, 2010-12-19

20 answers

Puedes usar number_format():

return number_format((float)$number, 2, '.', '');

Ejemplo:

$foo = "105";
echo number_format((float)$foo, 2, '.', '');  // Outputs -> 105.00

Esta función devuelve una cadena .

 829
Author: Codemwnci,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-18 07:58:26

Alternativamente,

$padded = sprintf('%0.2f', $unpadded); // 520 -> 520.00
 163
Author: Marc B,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-19 15:53:04

Uso round() (use si está esperando un número solo en formato flotante, de lo contrario use number_format () como respuesta dada por Codemwnci ):

echo round(520.34345,2);    // 520.34

echo round(520, 2);         // 520

Del manual:

Descripción:

float round ( float $val [, int $precision = 0 [, int $mode = PHP_ROUND_HALF_UP ]] );

Devuelve el valor redondeado de val a precision especificado (número de dígitos después del punto decimal). la precisión también puede ser negativa o cero (por defecto).

...

Ejemplo # 1 round() ejemplos

<?php
echo round(3.4);         // 3
echo round(3.5);         // 4
echo round(3.6);         // 4
echo round(3.6, 0);      // 4
echo round(1.95583, 2);  // 1.96
echo round(1241757, -3); // 1242000
echo round(5.045, 2);    // 5.05
echo round(5.055, 2);    // 5.06
?>

Ejemplo #2 ejemplos de modo

<?php
echo round(9.5, 0, PHP_ROUND_HALF_UP);   // 10
echo round(9.5, 0, PHP_ROUND_HALF_DOWN); // 9
echo round(9.5, 0, PHP_ROUND_HALF_EVEN); // 10
echo round(9.5, 0, PHP_ROUND_HALF_ODD);  // 9

echo round(8.5, 0, PHP_ROUND_HALF_UP);   // 9
echo round(8.5, 0, PHP_ROUND_HALF_DOWN); // 8
echo round(8.5, 0, PHP_ROUND_HALF_EVEN); // 8
echo round(8.5, 0, PHP_ROUND_HALF_ODD);  // 9
?>
 137
Author: Somnath Muluk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:26:24

Intenta:

$number = 1234545454; 
echo  $english_format_number = number_format($number, 2); 

La salida será:

1,234,545,454.00
 21
Author: Biju,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-11 07:21:08

Http://php.net/manual/en/function.round.php

Por ejemplo

echo round(5.045, 2);    // 5.05

echo round(5.055, 2);    // 5.06
 20
Author: SystemX17,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-31 20:06:33

Use la función PHP number_format().

 8
Author: Shamim Hafiz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-19 15:13:24

Puede usar funciones php printf o sprintf:

Ejemplo con sprintf:

$num = 2.12;
echo sprintf("%.3f",$num);

Puedes ejecutar lo mismo sin echo también, ex: sprintf("%.3f",$num);

Salida:

2.120

Alternativamente, con printf:

echo printf("%.2f",$num);

Salida:

2.124 
 8
Author: Aditya P Bhatt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-02 14:12:32

round_to_2dp es una función definida por el usuario, nada se puede hacer a menos que haya publicado la declaración de esa función

Sin embargo, mi conjetura es hacer esto number_format($number,2);

 6
Author: ajreal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-19 15:13:58

Otra forma más exótica de resolver este problema es usar bcadd() con un valor ficticio para eloper right_operand de 0.

$formatted_number = bcadd($number, 0, 2);
 6
Author: powtac,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-14 11:54:25

Hago la mía propia.

$decimals = 2;
$number = 221.12345;
$number = $number * pow(10,$decimals);
$number = intval($number);
$number = $number / pow(10,$decimals);
 5
Author: joanlgr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-20 10:19:06
$retailPrice = 5.989;
echo number_format(floor($retailPrice*100)/100,2, '.', ''); 

Devolverá 5.98 sin redondear el número.

 4
Author: mrphpguru,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-01 06:33:24
bcdiv($number, 1, 2) //2 varies for digits after decimal

Esto mostrará exactamente dos dígitos después del decimal.

Ventaja: Si desea mostrar solo dos dígitos después del valor flotante y no para int, use esto.

 4
Author: Wasim A.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-14 10:36:58
$number = sprintf('%0.2f', $numbers); // 520.89898989 -> 520.89

Esto le dará 2 número después del decimal.

 3
Author: S'copion Sam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-11 10:01:10

Si desea utilizar 2 dígitos decimales en todo su proyecto, puede definir

bcscale(2);

Entonces la siguiente función producirá el resultado deseado

$myvalue=10.165445;
echo bcadd(0,$myvalue);
//result=10.11

Pero si no usa la función bcscale, debe escribir el código de la siguiente manera para obtener el resultado deseado

  $myvalue=10.165445;
  echo bcadd(0,$myvalue,2);
 //result=10.11

Para saber más

 3
Author: jewelhuq,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-09 21:47:19

Use la función PHP number_format (). por ejemplo,

$num = 7234545423; 
echo number_format($num, 2); 

La salida será:

7,234,545,423.00

 3
Author: Sani Kamal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-21 07:51:20

Para redondeo condicional ie. mostrar decimal donde es realmente necesario de lo contrario número entero

123.56 => 12.56

123.00 => 123

$somenumber = 123.56;

$somenumber = round($somenumber,2);

if($somenumber == intval($somenumber))
{
    $somenumber = intval($somenumber);
}

echo $somenumber; // 123.56


$somenumber = 123.00;

$somenumber = round($somenumber,2);

if($somenumber == intval($somenumber))
{
    $somenumber = intval($somenumber);
}

echo $somenumber; // 123    
 3
Author: Viney,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-19 07:03:04
$twoDecNum = sprintf('%0.2f', round($number, 2));

El redondeo redondea correctamente el número y el sprintf lo fuerza a 2 decimales si resulta ser solo 1 decimal después del redondeo.

 2
Author: JohnS,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-24 21:19:39

Número sin ronda

$double = '21.188624';
echo intval($double).'.'.substr(end(explode('.',$double)),0,2);
 1
Author: Abhishek Sharma,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-17 12:44:27

Aquí tengo 2 decimales después .(punto) usando la función..

function truncate_number( $number, $precision = 2) {
    // Zero causes issues, and no need to truncate
    if ( 0 == (int)$number ) {
        return $number;
    }
    // Are we negative?
    $negative = $number / abs($number);
    // Cast the number to a positive to solve rounding
    $number = abs($number);
    // Calculate precision number for dividing / multiplying
    $precision = pow(10, $precision);
    // Run the math, re-applying the negative value to ensure returns correctly negative / positive
    return floor( $number * $precision ) / $precision * $negative;
}

Resultados de la función anterior:

echo truncate_number(2.56789, 1); // 2.5
echo truncate_number(2.56789);    // 2.56
echo truncate_number(2.56789, 3); // 2.567

echo truncate_number(-2.56789, 1); // -2.5
echo truncate_number(-2.56789);    // -2.56
echo truncate_number(-2.56789, 3); // -2.567

Nueva Respuesta Correcta

Use la función nativa de PHP bcdiv

echo bcdiv(2.56789, 1, 1);  // 2.5
echo bcdiv(2.56789, 1, 2);  // 2.56
echo bcdiv(2.56789, 1, 3);  // 2.567
echo bcdiv(-2.56789, 1, 1); // -2.5
echo bcdiv(-2.56789, 1, 2); // -2.56
echo bcdiv(-2.56789, 1, 3); // -2.567
 1
Author: Mr. HK,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-21 03:48:40

Puede usar la función PHP round().

echo round(3.4);         // 3
echo round(3.5);         // 4
echo round(3.6);         // 4
echo round(3.6, 0);      // 4
echo round(1.95583, 2);  // 1.96
echo round(1241757, -3); // 1242000
echo round(5.045, 2);    // 5.05
echo round(5.055, 2);    // 5.06
 -3
Author: Sadikhasan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-25 03:13:34