【问题标题】:"A non well formed numeric value encountered" when calling number_format调用 number_format 时“遇到格式不正确的数值”
【发布时间】:2016-11-26 13:01:23
【问题描述】:

我想在 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, ',', '.');
    }   
}

当我在视图中执行时:

<?php echo test_method($price) ?>

我收到了上述通知。如何解决?

【问题讨论】:

  • $price 里面有什么?
  • 数据库中的值
  • 喜欢
  • 使用我答案中的代码(更新为抛出异常),看看值是什么。果然不适合数字格式。您可能需要在格式化之前对其进行准备,或者确保仅将正确的值保存为价格。

标签: php codeigniter


【解决方案1】:

PHP 的 number_format() 接受 numeric 输入。确保 $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");
    }   
}

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

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

更新

$price 已格式化。显然,问题在于逗号:

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

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

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

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

【讨论】:

  • 当我在视图中调用时,结果为空白
  • 那是因为我注释掉了异常部分。立即尝试。
  • hmm,当我尝试直接调用 10000 时,它的工作,但是当我从我的数据库中调用该值时,会显示一个错误,例如 Invalid number to format: 524,800 而格式数据是 int in我的桌子
猜你喜欢
  • 2011-09-26
  • 1970-01-01
  • 2014-09-18
相关资源
最近更新 更多