【问题标题】:A non well formed numeric value encountered After Formatted by number_format() function由 number_format() 函数格式化后遇到的格式不正确的数值
【发布时间】:2019-01-01 06:40:26
【问题描述】:

我正在使用 Accessor 来格式化我的数字值。当我尝试计算格式化值时出现问题,因为 number_format() 函数返回一个字符串值。是否有任何替代方法来格式化数值并计算该值。

class Order extends Model

{
    protected $fillable = ['order_quantity'];

    public function getOrderQuantityAttribute($value)
    {
        return number_format($value);
    }
}

当我尝试计算时显示错误,

$order->order_quantity * 100;   
//$order->order_quantity value is 10,000

【问题讨论】:

    标签: laravel number-formatting php-7.2


    【解决方案1】:

    也许这会对你有所帮助。使用str_replace从字符串中删除逗号。

    $newOrderQuantity = str_replace(',', '', $order->order_quantity); // converting to "10000"
    

    以此类推,可以使用(int)$newOrderQuantity进行计算。

    【讨论】:

    • 谢谢!您的解决方案有效。还有一个问题。使用 Accessor 后是否仍然可以访问原始数据。
    • @Md.SukelAli 我没有得到确切的问题。可能您正在谈论获取原始原始数据(在使用访问器数据之前)。 $model->getOriginal('column-name-here');可以做到。
    • 谢谢。是的 !我说的是获取原始原始数据(在使用访问器数据之前)。
    • 使用这个:$model->getOriginal('column-name-here')
    【解决方案2】:

    只需将 ',' 替换为 '' :

       str_replace(',','',$order->order_quantity) *10
    

    【讨论】:

    • 执行此操作后 ((int) $order->order_quantity),它只返回 10。它一直工作到 (,) 来了。
    猜你喜欢
    • 1970-01-01
    • 2011-09-26
    • 2014-09-18
    相关资源
    最近更新 更多