在控制器中,我有:
return response()->json(
[
'number' => (float)8
],
Response::HTTP_OK,
[],
JSON_PRESERVE_ZERO_FRACTION
);这是输出:
{
"number": 8
}有没有可能得到8.0?这样做效果很好:
json_encode(['number' => (float)8],JSON_PRESERVE_ZERO_FRACTION);更新:当我将上面的response()->json设置为$variable,然后设置为print_r($variable)时,我得到的结果是:
(所以它看起来像是在工作,但在浏览器中返回时,我仍然得到8而不是8.0)
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] =>
)发布于 2018-02-08 17:29:53
使用number_format()
json_encode(['number' => number_format(8, 1)]);如果数字以字符串形式出现,请使用(float)$stringNumber而不是$stringNumber
https://stackoverflow.com/questions/48681894
复制相似问题