转换带有前导货币符号的数字字符串始终变为 0
我有这段代码并将货币前缀数字cast
转换为整数。
$t = "€2000";
$venc = (int)$t;
echo $venc; // actually echo is 0 and I want 2000 (remove symbol)
输出是 0
而不是 2000
,因此,代码未按我的预期工作。
(int)$t;
不回显 2000
的原因是什么?
I have this code and to cast
a currency-prefixed number to an integer.
$t = "€2000";
$venc = (int)$t;
echo $venc; // actually echo is 0 and I want 2000 (remove symbol)
The output is 0
and not 2000
, so, the code is not working as I expect.
What is the reason for (int)$t;
to not echo 2000
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
强制转换例程不会删除无效字符,而是从头开始并在到达第一个无效字符时停止,然后将其转换为数字,在您的情况下欧元符号无效并且它是第一个字符,因此结果数字为 0。
检查 http://www.php.net/manual/en/language.types.string.php#language.types.string.conversion
你可以尝试
(int)preg_replace('/\ D/u','',$t);
但是,如果您正在处理货币,您不应该忘记它们不是整数而是浮点数(尽管由于精度问题,使用浮点数表示货币并不是最好的主意,即0.1+ 0.2 !== 0.3)
(float)preg_replace('/[^0-9\.]/u','',$t);
casting routine does not remove invalid characters, but start from the beginning and stops when first invalid character is reached then convert it to number, in your case Euro sign is invalid and it is the first character thus resulting number is 0.
check http://www.php.net/manual/en/language.types.string.php#language.types.string.conversion
you could try
(int)preg_replace('/\D/u','',$t);
however if you are dealing with currencies you should not forget that they are not integers but floats (though using floats for currencies is not the best idea because of precision issues, i.e. 0.1 + 0.2 !== 0.3)
(float)preg_replace('/[^0-9\.]/u','',$t);
这可以帮助你
This can help you
使用 substr
use substr
使用 sscanf() 可以将以欧元货币符号为前缀的字符串解析为整数或浮点类型值,甚至可以处理负值。
在第一个参数中,对欧元符号进行硬编码,然后使用
%d
将以下数字子字符串解析为整数,或将%f
解析为浮点值。其他字符串函数不提供显式类型转换的好处。代码:(演示)
输出:
Parsing a string prefixed with the Euro currency symbol to an integer or float type value is cleanly done with
sscanf()
and will even handle negative values.In the first parameter, hardcode the Euro symbol, then use
%d
to parse the following numeric substring as an integer or%f
for a float value. Other string functions do not offer the benefit of explicit type casting.Code: (Demo)
Output: