number_format()導致錯誤“遇到非格式錯誤的數值”

[英]number_format() causes error “A non well formed numeric value encountered”


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)或number_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] [錯誤] [客戶端127.0.0.1] PHP注意:第41行/home/tahoang/Desktop/Projects/weatherData/weatherData.php中遇到的格式錯誤的數值

How to fix this?

如何解決這個問題?

4 个解决方案

#1


34  

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

嘗試將number_format()的第一個參數類型轉換為float:

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

or

要么

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

#2


4  

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);

#3


0  

I used this:

我用過這個:

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

Maybe it'll help someone out.

也許它會幫助別人。

#4


0  

Function is recognizing it as a string.

函數將其識別為字符串。

Convert to number by adding zero:

通過添加零轉換為數字:

number_format($NUMBER+0)

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2011/07/01/266de1415b62e41275032fb0ca01fa40.html



 
  © 2014-2022 ITdaan.com 联系我们: