PHP:格式在json_encode()函数中以给定的精度浮动 [英] PHP: format floats with given precision in json_encode() function

查看:125
本文介绍了PHP:格式在json_encode()函数中以给定的精度浮动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的问题(最初不太准确地制定):

There was my question (initially not so accurate formulated):

我需要在JSON字符串中使用PHP浮点数.代码:

I need to use PHP floats in JSON string. Code:

$obj['val'] = '6.40';
json_encode($obj);

转换为:

{"val": "6.40"}

没关系-我在PHP中具有字符串值"6.40",而在JSON中具有字符串值"6.40".

It's OK - I have string value '6.40' in PHP and I have string value "6.40" in JSON.

如果我需要使用浮点数,情况不是很好:

The situation is not so good if I need to use floats:

$obj['val'] = 6.40;
json_encode($obj);

转换为:

{"val": 6.4000000000000004}

但我需要:

{"val": 6.40}

如何以给定的精度将PHP浮点数转换为'json_encode'中的JSON数字?

How can I convert PHP floats to JSON number in 'json_encode' with given precision?

推荐答案

...,这是我自己的答案:

... and this is my own answer:

<?php
$obj['val'] = 6.40;
$out = json_encode($obj);
echo $out;  // {"val":6.4}

ini_set('precision', 17);
$obj['val'] = 6.40;
$out = json_encode($obj);
echo $out;  // {"val":6.4000000000000004}

ini_set('precision', 2);
$obj['val'] = 6.40;
$out = json_encode($obj);
echo $out;  // {"val":6.4}

这是@axiac的示例:

This is sample for @axiac:

ini_set('precision', 4);
$obj['val'] = 1/3;
$out = json_encode($obj);
echo $out;  // {"val":0.3333}

这篇关于PHP:格式在json_encode()函数中以给定的精度浮动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆