【问题标题】:php number is stored as string?php数字存储为字符串?
【发布时间】:2018-04-13 09:34:49
【问题描述】:

我正在使用 wordpress / woocommerce 并获得这样的产品价格:

$get_price = get_post_meta( $item_id, '_regular_price', true);

然后我正在计算折扣并像这样删除它:

$discount = 10;    
$minus = ($discount / 100) * $get_price;
$price = wc_price($get_price - $minus);

由于某种原因,我收到以下错误:

CRITICAL Uncaught Error: Unsupported operand types in ..... 

指向以 $minus = ... 开头的行

我使用“gettype”进行了一些挖掘,发现 woocommerce 价格存储为字符串,而不是整数。

然后我将上面的内容更改为这个以确保它现在是一个整数:

$discount = 10;    
$minus = ($discount / 100) * (int)$get_price;
$price = wc_price($get_price - $minus);

现在可以使用了,但它会将产品的价格从 13.97 英镑降低到 13.00 英镑。任何想法为什么会这样?以及为什么价格首先存储为字符串的任何原因?

编辑

我现在尝试了以下方法:

$get_price = get_post_meta( $item_id, '_regular_price', true);
$new_price = (float) $get_price;
echo gettype($new_price);

仍然返回字符串。

【问题讨论】:

  • 尝试使用(float) 而不是(int),但请注意,在货币计算中使用浮点运算是一种不好的做法——通过将值乘以(10^(needed precision + 1)) 将它们转换为整数,反转该计算为最终结果。
  • 您将价格转换为 int,因此它变为 13:3v4l.org/54O3T - 将价格作为浮点值处理是一种不好的做法,因为您会在任何地方遇到计算问题。
  • @LoicTheAztec 尝试了这个并且仍然作为字符串返回?
  • @danyo php-7.2 psysh 会话:>>> gettype((float)'13.97'); => "double
  • @LoicTheAztec 这无关紧要,$item_id = get_the_id();这是当前产品的 id。

标签: php wordpress string woocommerce integer


【解决方案1】:

$discount = '10'; 改成

$discount = 10;

$discount = '10'; 被视为字符串

你可以使用

 var_dump($discount);

检查数据类型

希望对你有帮助:-)

【讨论】:

  • 我使用 gettype($discount) 得到一个整数。那只是我的一个错字。折扣是 10 而不是“10”。
  • OPs 代码清楚地表明问题是$get_price,而不是$discount
  • @TomRegner 他已经编辑了这个问题,请在投票前检查编辑
  • @Ash-b 编辑无关紧要,如上所述的问题始终是$get_price 所需的演员,而不是$discount,引号对你来说是一个红鲱鱼。
猜你喜欢
  • 2016-10-16
  • 2012-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-28
  • 2018-07-04
  • 1970-01-01
相关资源
最近更新 更多