Tu Hoang
Tu Hoang

Reputation: 4712

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($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.

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

[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

How to fix this?

Upvotes: 25

Views: 67249

Answers (7)

Alejandro Fiore
Alejandro Fiore

Reputation: 1157

I struggle a lot with this error and it was because a return type float like this:

protected function example(): float {
   ...
   return number_format($number, 2);
}

The error was not the $number but the conversion of string with "." and "," in float when returning the string generated by number_format.

Upvotes: -1

Kaleemullah
Kaleemullah

Reputation: 534

I got this error when passing "0..6" in number_format() function.

I just replaced .. to . in price column of the table.

Upvotes: -1

Leo Chashchin
Leo Chashchin

Reputation: 91

When doing calculations, use

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

numer_format($value, 2)

Upvotes: 3

Elyor
Elyor

Reputation: 5532

Function is recognizing it as a string.

Convert to number by adding zero:

number_format($NUMBER+0)

Upvotes: 1

Matheno
Matheno

Reputation: 4142

I used this:

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

Maybe it'll help someone out.

Upvotes: 2

user2659841
user2659841

Reputation: 71

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

Upvotes: 7

Emre Yazici
Emre Yazici

Reputation: 10174

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

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

or

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

Upvotes: 68

Related Questions