Eliminar dígitos cero inútiles de decimales en PHP


Estoy tratando de encontrar una manera rápida de eliminar zero decimals de valores numéricos como este:

echo cleanNumber('125.00');
// 125

echo cleanNumber('966.70');
// 966.7

echo cleanNumber(844.011);
// 844.011

¿Existe alguna forma optimizada de hacer eso?

Author: vitto, 2013-01-26

19 answers

$num + 0 hace el truco.

echo 125.00 + 0; // 125
echo '125.00' + 0; // 125
echo 966.70 + 0; // 966.7

Internamente, esto es equivalente a lanzar para flotar con (float)$num o floatval($num) pero lo encuentro más simple.

 273
Author: lafor,
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-26 09:35:59

Solo puedes usar la función floatval

echo floatval('125.00');
// 125

echo floatval('966.70');
// 966.7

echo floatval('844.011');
// 844.011
 82
Author: DiverseAndRemote.com,
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-25 23:05:52

Simplemente agregando + a su variable de cadena causará encasillamiento a (float) y eliminará ceros:

echo +'125.00';  // 125
echo +'966.70';  // 966.7
echo +844.011;   // 844.011

var_dump(+'844.011asdf');  // double(844.011)
 13
Author: Alexander Yancharuk,
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-07 14:05:12

Esto es lo que uso:

function TrimTrailingZeroes($nbr) {
    return strpos($nbr,'.')!==false ? rtrim(rtrim($nbr,'0'),'.') : $nbr;
}

N.B. Esto asume que . es el separador decimal. Tiene la ventaja de que funcionará en números arbitrariamente grandes (o pequeños) ya que no hay un molde flotante. Tampoco convertirá los números en notación científica (por ejemplo, 1.0 E-17).

 13
Author: mpen,
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-11-17 19:06:10

Deberías lanzar tus números como carrozas, lo que hará esto por ti.

$string = "42.422005000000000000000000000000";
echo (float)$string;

La salida de esto será lo que está buscando.

42.422005

 8
Author: Sajan Parikh,
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-25 23:07:49
$x = '100.10'; 
$x = preg_replace("/\.?0*$/",'',$x); 
echo $x;

No hay nada que no se pueda arreglar con una expresión regular simple;)

Http://xkcd.com/208/

 8
Author: Dakkaron,
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-02-12 10:52:30

Para todos los que vienen a este sitio que tienen el mismo problema con commata en su lugar, puede cambiar:

$num = number_format($value, 1, ',', '');

A

$num = str_replace(',0', '', number_format($value, 1, ',', '')); // e.g. 100,0 becomes 100

Esto me ayudó, y supongo que no estoy solo.

Si hay que eliminar dos ceros:

A

$num = str_replace(',00', '', number_format($value, 2, ',', '')); // e.g. 100,00 becomes 100

Más aquí: Número PHP: punto decimal visible solo si es necesario

 7
Author: Kai Noack,
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:07

Si desea eliminar los dígitos cero justo antes de mostrar en la página o plantilla.

Puedes usar la función sprintf ()

sprintf('%g','125.00');
//125

‌‌sprintf('%g','966.70');
//966.7

‌‌‌‌sprintf('%g',844.011);
//844.011
 5
Author: Hemerson Varela,
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-04-11 20:58:04

Encasillado a float.

$int = 4.324000;
$int = (float) $int;
 3
Author: Joseph 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
2016-08-03 13:25:41

Forma complicada pero funciona:

$num = '125.0100';
$index = $num[strlen($num)-1];
$i = strlen($num)-1;
while($index == '0') {
   if ($num[$i] == '0') {
     $num[$i] = '';
     $i--;
   }

   $index = $num[$i];
}

//remove dot if no numbers exist after dot
$explode = explode('.', $num);
if (isset($explode[1]) && intval($explode[1]) <= 0) {
   $num = intval($explode[0]);
}

echo $num; //125.01

Las soluciones anteriores son la forma óptima, pero en caso de que desee tener su propia podría utilizar esto. Lo que hace este algoritmo comienza al final de la cadena y comprueba si su 0, si lo es, se establece en cadena vacía y luego va al siguiente carácter desde atrás hasta que el último carácter es > 0

 1
Author: GGio,
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-25 23:26:39

Extraño, cuando obtengo un número de la base de datos con un tipo "float" y si mi número es ex. 10000 cuando flotar, se convierte en 1.

$number = $ad['price_month']; // 1000 from the database with a float type
echo floatval($number);
Result : 1

He probado todas las soluciones anteriores, pero no funcionó.

 1
Author: lio,
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-05-24 07:01:26

Debido a esta pregunta es vieja. Primero, lo siento por esto.

La pregunta es sobre el número xxx.xx pero en caso de que sea x,xxx.xxxxx o separador decimal de diferencia como xxxx,xxxx esto puede ser más difícil de encontrar y eliminar dígitos cero del valor decimal.

/**
 * Remove zero digits from decimal value.
 * 
 * @param string|int|float $number The number can be any format, any where use in the world such as 123, 1,234.56, 1234.56789, 12.345,67, -98,765.43
 * @param string The decimal separator. You have to set this parameter to exactly what it is. For example: in Europe it is mostly use "," instead of ".".
 * @return string Return removed zero digits from decimal value.
 */
function removeZeroDigitsFromDecimal($number, $decimal_sep = '.')
{
    $explode_num = explode($decimal_sep, $number);
    if (is_array($explode_num) && isset($explode_num[count($explode_num)-1]) && intval($explode_num[count($explode_num)-1]) === 0) {
        unset($explode_num[count($explode_num)-1]);
        $number = implode($decimal_sep, $explode_num);
    }
    unset($explode_num);
    return (string) $number;
}

Y aquí está el código para la prueba.

$numbers = [
    1234,// 1234
    -1234,// -1234
    '12,345.67890',// 12,345.67890
    '-12,345,678.901234',// -12,345,678.901234
    '12345.000000',// 12345
    '-12345.000000',// -12345
    '12,345.000000',// 12,345
    '-12,345.000000000',// -12,345
];
foreach ($numbers as $number) {
    var_dump(removeZeroDigitsFromDecimal($number));
}


echo '<hr>'."\n\n\n";


$numbers = [
    1234,// 12324
    -1234,// -1234
    '12.345,67890',// 12.345,67890
    '-12.345.678,901234',// -12.345.678,901234
    '12345,000000',// 12345
    '-12345,000000',// -12345
    '12.345,000000',// 12.345
    '-12.345,000000000',// -12.345
    '-12.345,000000,000',// -12.345,000000 STRANGE!! but also work.
];
foreach ($numbers as $number) {
    var_dump(removeZeroDigitsFromDecimal($number, ','));
}
 1
Author: vee,
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-12-18 08:22:59

Puedes usar:

print (floatval)(number_format( $Value), 2 ) );    
 0
Author: MUNEERPASHA GADAD,
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-10-20 08:07:10
$str = 15.00;
$str2 = 14.70;
echo rtrim(rtrim(strval($str), "0"), "."); //15
echo rtrim(rtrim(strval($str2), "0"), "."); //14.7
 0
Author: MSTRmt,
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-23 15:00:50

Esa es mi pequeña solución... Puede incluirse en una clase y establecer vars

Private d dsepparator='.'; // decimal private t tsepparator=','; / / thousand

Que puede ser establecido por constructor y cambiar a users lang.

class foo
{
    private $dsepparator;
    private $tsepparator;

    function __construct(){
        $langDatas = ['en' => ['dsepparator' => '.', 'tsepparator' => ','], 'de' => ['dsepparator' => ',', 'tsepparator' => '.']];
        $usersLang = 'de'; // set iso code of lang from user
        $this->dsepparator = $langDatas[$usersLang]['dsepparator'];
        $this->tsepparator = $langDatas[$usersLang]['tsepparator'];
    }

    public function numberOmat($amount, $decimals = 2, $hideByZero = false)
    {
        return ( $hideByZero === true AND ($amount-floor($amount)) <= 0 ) ? number_format($amount, 0, $this->dsepparator, $this->tsepparator) : number_format($amount, $decimals, $this->dsepparator, $this->tsepparator);
    }
    /*
     * $bar = new foo();
     * $bar->numberOmat('5.1234', 2, true); // returns: 5,12
     * $bar->numberOmat('5', 2); // returns: 5,00
     * $bar->numberOmat('5.00', 2, true); // returns: 5
     */

}
 0
Author: Paykoman,
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-12-31 08:03:10

Tenga cuidado con agregar +0.

echo number_format(1500.00, 2,".",",")+0;
//1

El resultado de esto es 1.

echo floatval('1,000.00');
// 1

echo floatval('1000.00');
//1000
 0
Author: OnionStand,
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-01-19 15:18:10

Esta es mi solución. Quiero mantener la capacidad de agregar miles separador

    $precision = 5;    
    $number = round($number, $precision);
    $decimals = strlen(substr(strrchr($number, '.'), 1));
    return number_format($number, $precision, '.', ',');
 0
Author: despotbg,
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-09-11 16:16:16

Este Código eliminará el cero después del punto y devolverá solo dos dígitos decimales.

Number número = 1200.0000;
str_replace (".00',", number_format (number number, 2,'.', ''));

La Salida será: 1200

 -1
Author: Ashish pathak,
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-03 08:58:38
$value = preg_replace('~\.0+$~','',$value);
 -1
Author: Nikhil Gyan,
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-09-25 06:30:52