Formatting with float type
When the variable does not have the value inside quotes, the Zeros on the right are omitted "automatically"
$n = 100.00;
echo $n; // retorna 100
$n = 100.30;
echo $n; // retorna 100.3
When it is delimited by single quotes or double quotes, it is treated as a string at the time of printing. The above examples would return 100.00 and 100.30, respectively.
Therefore, if it is not important to display zero when there is a fractional value, 100.30, just do not delineate with quotation marks.
If not possible, you need to cast.
There are various forms that return the same result:
$n = '100.30';
echo (float)$n; // retorna 100.3
$n = '100.30';
echo floatval($n); // retorna 100.3
$n = '100.30';
echo $n + 0; // retorna 100.3
$n = '100.30';
echo +$n; // retorna 100.3
*The more "cute" or "short" option doesn’t mean it’s faster.
Formatting the string type
If you still want to display zero to the right of a fractional value, one option is to make a formatting that identifies such a condition.
// O valor pode ser número ou string
//$n = '100.00';
//$n = 100.00;
//$n = '100.30';
$n = 100.30;
// Garante que a formatação mantenha 2 casas decimais
$n = number_format($n, 2, '.', '');
// Abstrai a parte decimal
$d = substr($n, -2);
// Se for 00, então, faz o cast para removê-los
if ($d === '00') {
$n = (float)$n;
}
// Imprime o resultado
echo $n;
In a more succinct way, you can do just that
$n = str_replace('.00', '', number_format($n, 2, '.', ''));
echo $n;
You already have an answer to this question at stackoverflow. http://stackoverflow.com/q/14531679/2370479
– Diego Henrique
Exactly. Take a look at the floatval function()
– Humba
Good night is right, thank you
– Junior