PHP - floatval 削减小数点后的位置?
我有这个 PHP 代码:
<?php
$float = "1,99";
echo "<p>$float<br>";
$float = floatval($float); // Without this line number_format throws a notice "A non well formed numeric value encountered" / (float) $float leads to the same output
$val = number_format($float, 2,'.', ',');
echo "$float</p>";
?>
为什么它返回 1?别明白。
并且:是的,将 1,99 转换为 1,99 是有意义的;-)
感谢您的建议...
I have this PHP code:
<?php
$float = "1,99";
echo "<p>$float<br>";
$float = floatval($float); // Without this line number_format throws a notice "A non well formed numeric value encountered" / (float) $float leads to the same output
$val = number_format($float, 2,'.', ',');
echo "$float</p>";
?>
Why does it return 1? Don't get that.
And: yes, there is a sense in converting 1,99 to 1,99 ;-)
Thanks for advise...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题是,PHP 无法将
1,99
中的,
识别为小数点分隔符。float
类型定义为具有以下 正式定义:这意味着它只接受
.
作为小数点分隔符。事实上,这与number_format
对无效数据类型发出警告的原因相同,因为它无法在内部将1,99
转换为float
。以下应该有效:
The problem is, that PHP does not recognize the
,
in1,99
as a decimal separator. Thefloat
type is defined as having the following formal definition:That means it'll only accept
.
as a decimal separator. That's in fact the same reason whynumber_format
throws a warning on an invalid datatype because it cannot convert1,99
to afloat
internally.The following should work:
floatval 将逗号 (,) 识别为字符而不是数字,因此它会截断其后面的所有内容。在本例中,即 99。请使用点 (.) 而不是逗号 (,),这样可能会起作用。
floatval 示例(来源:http://php.net/manual/en/function.floatval。 php):
floatval recognizes the comma (,) as a character and not as a number, so it cuts off everything that comes after it. In this case, that's the 99. Please use a dot (.) instead of a comma (,) and it will probably work.
Example floatval (source: http://php.net/manual/en/function.floatval.php):
1,99 不是有效的 php 浮点数。问题是你的逗号(,)。在 PHP 中,必须使用点 (.) 作为浮点分隔符。
1,99 is not a valid php float. The issue is your comma (,). In PHP you have to use dot (.) as floating point separator.