Php返回浮动货币格式

时间:2018-06-11 08:34:39

标签: php

只是尝试从我们的API返回json中的价格,这需要格式化为带有两个小数位的浮点数。目前,当我浮动它返回没有小数但没有浮点数它返回一个字符串,我希望它作为一个浮点数。

public function repairs(Collection $repairs) : Collection
{
    return $repairs->map(function ($repair) {
        return [
            "id" => $repair->id,
            "title" => $repair->problem->title,
            "price" => (float) $repair->price
        ];
    });
}

结果:

"repairs": {
    "411": {
        "id": 411,
        "title": "Screen",
        "price": 235.99
    },
    "419": {
        "id": 419,
        "title": "Charger Port",
        "price": 40
    },
    "582": {
        "id": 582,
        "title": "Back Glass",
        "price": 40
    }
}

1 个答案:

答案 0 :(得分:0)

您可以使用round()或number_format()。 Round返回一个float,number_format返回一个字符串。所以你可能更喜欢round():

    public function repairs(Collection $repairs) : Collection
    {
        return $repairs->map(function ($repair) {
            return [
                "id" => $repair->id,
                "title" => $repair->problem->title,
                "price" =>  round($repair->price,2)
            ];
        });
    }