Chris Lumbberg Chris Lumbberg - 13 days ago 6
PHP Question

"A non well formed numeric value encountered" when calling number_format

I want to create my own number formatter helper in Codeigniter. But when I call my function, it shows an error:


Severity: Notice

Message: A non well formed numeric value encountered


Here is my helper function:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

if ( ! function_exists('test_method'))
{
function test_method($var = '')
{
return number_format( (float) $var, 0, ',', '.');
}
}


When I execute in view:

<?php echo test_method($price) ?>


I get the mentioned notice. How to fix it?

Answer

PHP's number_format() accepts a numeric input. Make sure $price is numeric.

if ( ! function_exists('test_method'))
{
    function test_method($var)
    {
        if (is_numeric($var)) {
            return number_format($var);
        }

        // Invalid input, do something about it.
        throw new \Exception("Invalid number to format: $var");
    }   
}

And your default value for $var is not a very good choice:

>>> number_format('')
PHP warning:  number_format() expects parameter 1 to be float, string given on line 1

Update

The $price is already formatted. Obviously, the problem is that comma:

>>> number_format("524,800")
PHP error:  A non well formed numeric value encountered on line 1

As you're saving prices with separators (seems to be already formatted), first you need to drop them before number formatting them:

if ( ! function_exists('test_method'))
{
    function test_method($var)
    {
        // Prep
        $var = str_replace(',', '', $var);

        if (is_numeric($var)) {
            return number_format($var);
        }

        // Invalid input, do something about it.
        throw new \Exception("Invalid number to format: $var");
    }   
}

Think twice; it's not a good practice to save prices as formatted strings. Or if that's not your case, then you r data is being formatted somewhere else along the way before it hits your helper. Eaither way, you need to fix it.