调用 number_format 时“遇到格式不正确的数值”

Chr*_*erg 1 php codeigniter

我想在 Codeigniter 中创建自己的数字格式化程序助手。但是当我调用我的函数时,它显示错误:

严重性:通知
消息:遇到格式不正确的数值

这是我的辅助函数:

<?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, ',', '.');
    }   
}
Run Code Online (Sandbox Code Playgroud)

当我在视图中执行时:

<?php echo test_method($price) ?>
Run Code Online (Sandbox Code Playgroud)

我收到了上述通知。如何修复它?

sep*_*ehr 5

PHPnumber_format()接受数字输入。确保$price是数字。

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");
    }   
}
Run Code Online (Sandbox Code Playgroud)

而你的默认值$var并不是一个很好的选择:

>>> number_format('')
PHP warning:  number_format() expects parameter 1 to be float, string given on line 1
Run Code Online (Sandbox Code Playgroud)

更新

已经$price格式化了。显然,问题出在逗号上:

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

当您使用分隔符保存价格时(似乎已经格式化),首先您需要在对它们进行数字格式化之前删除它们:

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");
    }   
}
Run Code Online (Sandbox Code Playgroud)

三思而后行;将价格保存为格式化字符串并不是一个好习惯。或者,如果这不是您的情况,那么您的数据在到达您的助手之前正在其他地方进行格式化。无论哪种方式,你都需要修复它。