doujiaci7976 2017-04-20 22:58
浏览 29

PHP - 隐式类型处理不起作用?

I'm importing an Excel file.

The file has mixed data types - item code, currency values, dates.

The item codes can have leading zeroes, so I'm using:

$objPHPExcel->getActiveSheet()->toArray('', false, true, false);

As you would expect, this is retaining the leading zeroes, and is also retaining number formatting: 12,345.00

The problem is that we need certain numbers in float format, to perform operations on them.

For some reason, PHP isn't performing implicit type conversion.

e.g.:

$value = "21,356.00";
$newvalue =  $value * 2;

This returns: 42. I expected it to return 42712.00.

Why is this happening?

With the excel file, we only know which column contains the item codes. The other columns can be anything, so I can't just parse float across them all. We identify them by the header row in the file.

Ideally we need to implicit type conversion to work.

Any suggestions?

  • 写回答

1条回答 默认 最新

  • dpkt31779 2017-04-21 02:43
    关注

    If you try to use a string like "22,345.43" as a float in PHP, it will discard everything behind the first comma and convert it to a 22. If you try to use a currency formatted string like "$ 22,234.45" it will be converted to 0.

    To avoid this, you need this function: http://php.net/manual/es/function.floatval.php#114486

    Note: you don't need floatval, you need to use toFloat($num) in the first "user-contributed" note.

    That function takes a string with any formatted number on it, detects the last dot or comma, and uses that last separator to parse the number. The function also ignores everything but digits, so it's useful to remove currencies and thousands separators.

    It's not a native PHP function so you will have to include that function in your code to be able to use it.

    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?