1

我试图显示产品的价格,当价格是一个整数时,不显示小数点“.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`"
4

5 回答 5

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 考虑了将字符串转换为小数时的任何舍入错误。

于 2013-01-26T05:44:19.900 回答
0

尝试仅删除“0”参数。无论如何,它默认为它。

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

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

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

于 2013-01-26T05:44:43.973 回答
0

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

$to_print = (int) $price_value;
于 2013-01-26T05:45:54.320 回答
0

rather than is_int() (which returns false work on strings), consider using 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);

It probably doesn't work as well for higher-precision numbers, but I tested it with a few reasonable price values and it seems to work okay.

于 2013-01-26T06:08:25.303 回答
0

you can try this little class : https://github.com/johndodev/MoneyFormatter

于 2014-02-17T13:29:57.203 回答