首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JsonResponse选项参数

JsonResponse选项参数
EN

Stack Overflow用户
提问于 2018-02-08 17:26:30
回答 1查看 602关注 0票数 2

在控制器中,我有:

代码语言:javascript
复制
return response()->json(
    [
        'number' => (float)8
    ],
    Response::HTTP_OK,
    [],
    JSON_PRESERVE_ZERO_FRACTION
);

这是输出:

代码语言:javascript
复制
{
    "number": 8
}

有没有可能得到8.0?这样做效果很好:

代码语言:javascript
复制
json_encode(['number' => (float)8],JSON_PRESERVE_ZERO_FRACTION);

更新:当我将上面的response()->json设置为$variable,然后设置为print_r($variable)时,我得到的结果是:

(所以它看起来像是在工作,但在浏览器中返回时,我仍然得到8而不是8.0)

代码语言:javascript
复制
Illuminate\Http\JsonResponse Object
(
    [data:protected] => {"number":8.0}
    [callback:protected] => 
    [encodingOptions:protected] => 1024
    [headers] => Symfony\Component\HttpFoundation\ResponseHeaderBag Object
        (
            [computedCacheControl:protected] => Array
                (
                    [no-cache] => 1
                    [private] => 1
                )

            [cookies:protected] => Array
                (
                )

            [headerNames:protected] => Array
                (
                    [cache-control] => Cache-Control
                    [date] => Date
                    [content-type] => Content-Type
                )

            [headers:protected] => Array
                (
                    [cache-control] => Array
                        (
                            [0] => no-cache, private
                        )

                    [date] => Array
                        (
                            [0] => Thu, 08 Feb 2018 11:27:34 GMT
                        )

                    [content-type] => Array
                        (
                            [0] => application/json
                        )

                )

            [cacheControl:protected] => Array
                (
                )

        )

    [content:protected] => {"number":8.0}
    [version:protected] => 1.0
    [statusCode:protected] => 200
    [statusText:protected] => OK
    [charset:protected] => 
    [original] => Array
        (
            [number] => 8
        )

    [exception] => 
)
EN

回答 1

Stack Overflow用户

发布于 2018-02-08 17:29:53

使用number_format()

代码语言:javascript
复制
json_encode(['number' => number_format(8, 1)]);

如果数字以字符串形式出现,请使用(float)$stringNumber而不是$stringNumber

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48681894

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档