0

I am getting the following error as a result of a calculation. I couldn't see any problem with the exit code. So why am I getting this error and how can I fix it?

// b2Cost = 19.020843;

return (float)number_format((float)str_replace(",", ".", $b2Cost), 2, ".", "");

Error:

Notice: A non well formed numeric value encountered 
Emre7
  • 21
  • 5
  • 1
    Why do you `number_format` in between there, and then cast that to `(float)` again? – Markus AO May 03 '22 at 18:49
  • https://3v4l.org/f9Iqe you're getting a notice, but it still works as expected. It's letting you know that [str_replace](https://www.php.net/manual/en/function.str-replace.php) is expecting a string as the 3rd parameter, but you're passing a float. So it's converting it to a string and continuing. – WOUNDEDStevenJones May 03 '22 at 18:53
  • Thank you for your answer but I guess there is no way to turn off this notification except `display_errors` @WOUNDEDStevenJones – Emre7 May 03 '22 at 19:11
  • Or, like the answer below suggests, convert this to a string before the function gets called. A quick and dirty way is `str_replace(",", ".", $b2Cost."")`, which is functionally the same as `str_replace(",", ".", (string) $b2Cost)` or `str_replace(",", ".", strval($b2Cost))` – WOUNDEDStevenJones May 03 '22 at 19:31
  • @WOUNDEDStevenJones I understand, thanks you for your time and comments – Emre7 May 03 '22 at 19:38

1 Answers1

0

Try

return (float)number_format((float)str_replace(",", ".", (string) $b2Cost), 2, ".", "");

But if you just want to shorten the float, take a look at https://www.php.net/manual/en/function.round.php

Guido Faecke
  • 644
  • 1
  • 3
  • 7
  • 2
    For clarification to readers, `str_replace` calls for a string subject, but `$b2Cost` is instantiated as an integer. The answer here [typecasts](https://www.php.net/manual/en/language.types.type-juggling.php#language.types.typecasting) the integer variable as a string, using `(string)$b2Cost`, to satisfy `str_replace` requirements. (Guido, best to explain your answer.) – bloodyKnuckles May 03 '22 at 18:50