首页 > 解决方案 > APi解析小数点后2位?

问题描述

我有一个代码可以通过 API 更新 Steam 服务游戏中的项目列表。作为回应,这些价格在我看来是这样的"price":0.64000000000000001,"count":897,"bprice":0.080000000000000002:如何在 API 解析阶段使值pricebprice小数点后有 2 位数字?

我的解析代码:

public static function updatePrices()
{
    if ($data = json_decode(file_get_contents(self::STEAMP)) ?? false) {
        if ($data->success) {

            $items_in_res = new \stdClass();
            foreach($data->items as $key => $item) {
                if ($item->count > 50  ) {
                    if ($item->bcount > 20) {
                        if ($item->price <= 1) {
                            $item->price = 0.64;
                        }
                        $items_in_res->$key = $item;
                    }
                }
            }

            Storage::disk('local')->put(self::Prices, json_encode([
                'time' => time(),
                'items' => $items_in_res
            ]));

            return $items_in_res;
        } else {
            \Log::error('Error: ' . $data->message);
            return false;
        }
    } else {
        \Log::error('Error updating prices!');
        return false;
    }
}

标签: php

解决方案


你可以用number_format这个。

echo number_format($item->price,2);

演示: https ://3v4l.org/NnZlb

只是一个侧面说明number_formatrounds silently


推荐阅读