在PHP中,如何打印带有2个小数的数字,但是仅当已经有小数时才打印?

| 我有一个基本的index.php页面,其中包含一些要在多个位置打印的变量-这是变量:
<?php
  $firstprice = 1.50;
  $secondprice = 3.50;
  $thirdprice = 20;
?>
我的挑战是,在文档的后面,当我打印时,我得到的价格中没有价格中的第二个“ 0”,这是发生的情况:
<?php print \"$firstprice\";?> // returns 1.5 - not 1.50!
所以-我知道如何用JS做到这一点,但是如何在PHP 5+中完成呢?基本上,我想打印第二个\'0 \'(如果已经有一个小数),因此如果变量等于\'3 \',则它保持为\'3 \',但如果等于\\ '3.5 \',它转换为显示\'3.50 \',第二个\'0 \',依此类推。 这是一个JS示例-PHP等效项是什么? JS:
.toFixed(2).replace(/[.,]00$/, \"\"))
非常感谢!!     
已邀请:
这很简单,它还可以让您调整格式以进行品尝:
$var = sprintf($var == intval($var) ? \"%d\" : \"%.2f\", $var);
如果没有小数,则将变量格式化为整数(
%d
),如果具有小数部分,则将正好具有两位十进制数字(
%.2f
)。 看到它在行动。 更新:正如Archimedix指出的,如果输入值在
(2.995, 3.005)
范围内,这将导致显示
3.00
。这是一个改进的检查,可以解决此问题:
$var = sprintf(round($var, 2) == intval($var) ? \"%d\" : \"%.2f\", $var);
    
<?php

$number = 1234.56;

// english notation (default)
$english_format_number = number_format($number);
// 1,235

// French notation
$nombre_format_francais = number_format($number, 2, \',\', \' \');
// 1 234,56

$number = 1234.5678;

// english notation without thousands seperator
$english_format_number = number_format($number, 2, \'.\', \'\');
// 1234.57

?>
更多信息在这里 http://php.net/manual/zh/function.number-format.php     
你可以用
   if (is_float($var)) 
   {
     echo number_format($var,2,\'.\',\'\');
   }
   else
   {
     echo $var;
   }
    
那么这样的事情呢:
$value = 15.2; // The value you want to print

$has_decimal = $value != intval($value);
if ($has_decimal) {
    echo number_format($value, 2);
}
else {
    echo $value;
}
注意事项: 您可以使用
number_format()
将值格式化为两位小数 如果值是整数,则显示它。     
您可以使用number_format():
echo number_format($firstprice, 2, \',\', \'.\');
    
另一种打印方式
$number = sprintf(\'%0.2f\', $numbers); 
   // 520.89898989 -> 520.89
    

要回复问题请先登录注册