Search code examples
phpstringdecimal

php number format error - number_format() expects parameter 1 to be float, string given


Can you please someone help me with this code I got

Number_format() expects parameter 1 to be float, string given

my Code:

public static function format_inr($value, $decimals = 0) {
    setlocale(LC_MONETARY, 'en_IN');
    if (function_exists('money_format')) {
        return money_format('%!i.' . $decimals . 'i', round($value));
    } else {
        return number_format($value, 2);
    }
}

Solution

  • You can fix this with casting the content of the variable $value into float. So if the type of $value is not float, you can force PHP to interpret the content as float.

    public static function format_inr($value, $decimals = 0) {
        // ...
            return number_format((float) $value, 2);
        // ..
    }
    

    as a side node: I guess it's better to use type hints for the function. so you expect $value as float in the function call, so every method caller was instructed to call the method with a float, not a string or an integer. So you don't need to cast the variable again, because you are sure you getting a float. the method caller has to be take care of casting, if needed.

    public static function format_inr(float $value, $decimals = 0) {
        // ...
            return number_format($value, 2);
        // ..
    }