php number_format() 导致错误“遇到格式不正确的数值”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6542403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:41:06  来源:igfitidea点击:

number_format() causes error "A non well formed numeric value encountered"

phpnumber-formatting

提问by Tu Hoang

I am using number_format to round floats to only 2 decimal digits. The problem is that some of my inputs don't have more than 2 decimals digits to begin with. So the code:

我正在使用 number_format 将浮点数四舍五入到只有 2 个十进制数字。问题是我的一些输入开始时没有超过 2 个小数位。所以代码:

number_format($value, 2)

Instead of peacefully adding 0 in case it doesn't have enough decimal digits, it raises errors inside Apache log and that's not desirable.

如果没有足够的十进制数字,它不是和平地添加 0,而是在 Apache 日志中引发错误,这是不可取的。

So number_format(2.1, 2)or number_format(0, 2)will raise error in Apache log.

所以number_format(2.1, 2)ornumber_format(0, 2)会在 Apache 日志中引发错误。

[Thu Jun 30 17:18:04 2011] [error] [client 127.0.0.1] PHP Notice: A non well formed numeric value encountered in /home/tahoang/Desktop/Projects/weatherData/weatherData.php on line 41

[Thu Jun 30 17:18:04 2011] [error] [client 127.0.0.1] PHP 注意:在第 41 行的 /home/tahoang/Desktop/Projects/weatherData/weatherData.php 中遇到格式不正确的数值

How to fix this?

如何解决这个问题?

回答by Emre Yazici

Try type casting first parameter of number_format()to float:

尝试将number_format() 的第一个参数转换为浮点数:

$format = number_format((float)0, 2);

or

或者

$format = number_format(floatval(0), 2);

回答by user2659841

Try to replace decimal point and after that cast to float.

尝试替换小数点,然后转换为浮点数。

var_dump((float)number_format((float)str_replace(",", ".", "20,5"), 2, ".", ""));
result: float(20.5);

Without replacing:

无需更换:

var_dump((float)number_format(floatval("20,5"), 2, ".", ""));
result: float(20);
var_dump((float)number_format((float) "20,5", 2, ".", ""));
result: float(20);

回答by Leo Chashchin

When doing calculations, use

进行计算时,使用

number_format($value, 2, ".", "")

number_format($value, 2, ".", "")

And if you would like to display numbers with .00 at the end (like "50.50" not "50.5") then you would use

如果您想在末尾显示 .00 的数字(例如“50.50”而不是“50.5”),那么您可以使用

numer_format($value, 2)

numer_format($value, 2)

回答by Matheno

I used this:

我用过这个:

str_replace(array(".", ","), array(",", "."), $value)

Maybe it'll help someone out.

也许它会帮助某人。

回答by Elyor

Function is recognizing it as a string.

函数将其识别为字符串。

Convert to number by adding zero:

通过添加零转换为数字:

number_format($NUMBER+0)