需要显示没有小数的价格

时间:2013-01-26 05:41:01

标签: php formatting numbers

我试图显示产品的价格,当价格是一个整数值时,不显示小数“.00”;但是当前结果总是显示小数值。 我在下面提供了我现在的逻辑;

$price_value = "20.00"; //coming from DB as string


if (is_int($price_value)) {

   //Display whole number without decimal
   $to_print = number_format($price_value,0);

else {
  //Show the decimal value
  $to_print = number_format($price_value,2);

}

//When I print this value I always get "`20.00`" not "`20`"

5 个答案:

答案 0 :(得分:3)

由于您转换了字符串,因此该变量不被视为整数。

参见例如:

php > var_dump(is_int("23.0"));
bool(false)
php > var_dump(is_int("23"));
bool(false)
php > var_dump(is_int(23));
bool(true)

您可以改为执行以下操作:

if( abs($price_value - floor($price_value)) < 0.001 )
  //Display whole number without decimal
  $to_print = number_format($price_value,0);
else {
  //Show the decimal value
  $to_print = number_format($price_value,2);
}

0.001考虑了将字符串转换为小数时的任何舍入误差。

答案 1 :(得分:0)

尝试删除'0'参数。它无论如何都默认为它。

如果这不起作用且你坚持这样做,你可以添加所有参数:

string number_format ( float $number , int $decimals = 0 , string $dec_point = '.' , string $thousands_sep = ',' ) 

并将dec_point设置为可用于拆分的字符值,然后将字符串返回到该点。首先检查第一个想法是否有效。

答案 2 :(得分:0)

您可以用来打印没有小数的值

$to_print = (int) $price_value;

答案 3 :(得分:0)

而不是is_int()(对字符串返回false工作),请考虑使用fmod()

$price_value = "20.00";
if (fmod($price_value,1) === 0.0)
    $to_print = number_format($price_value,0);
else
    $to_print = number_format($price_value,2);

对于更高精度的数字,它可能不起作用,但我用一些合理的价格值测试它,它似乎工作正常。

答案 4 :(得分:0)

你可以尝试这个小班:https://github.com/johndodev/MoneyFormatter

相关问题