四舍五入的浮点数返回所有小数

Rounded float is returned with all decimals

提问人:Simone Conti 提问时间:4/8/2019 更新时间:4/8/2019 访问量:182

问:

我有一个 rest 端点,它返回一些简单的统计数据:总票数、平均票数,...

function getRatings($data) {
  global $wpdb;
  $struttura_id = intval( $data['struttura_id'] );

  $sql = " SELECT COUNT(M.meta_key) as num_votes, SUM(M.meta_value) as tot_votes
           FROM .... ";

  $stats = $wpdb->get_row($sql);

  return array('struttura_id'=>$struttura_id, 
               'num_votes' => $stats->num_votes, 
               'tot_votes'=> $stats->tot_votes, 
               'average'=> round($stats->tot_votes/$stats->num_votes,1) );
}

出于某种原因,当我收到平均值作为 WP rest API 的 REST 响应时,平均值没有四舍五入。

响应是:

{
  "struttura_id": 115,
  "num_votes": "3",
  "tot_votes": "10",
  "average": 3.2999999999999998
}

正如你所看到的,平均值非常“奇怪”。小数点太多和精度错误(一个好的值应该是 3.33333333)

怎么了?

舍入 浮动精度 wordpress-rest-api

评论

0赞 Eric Postpischil 4/8/2019
(a) 我假设给定的函数旨在返回四舍五入到小数位。如果是这样,您使用的事实解释了为什么结果接近 3.3 而不是 31/3。要获得更准确的结果,请删除 .(b) 您使用的浮点格式使用2的幂的倍数表示数字。3.3 不能以这种格式准确表示;任何计算都无法精确地产生 3.3。您必须接受近似值或使用不同的格式(这意味着实现自己的格式,而不是使用内置语言格式)。roundround(x, n)xnround(…, 1)round
0赞 Eric Postpischil 4/8/2019
另一方面,如果您可以在程序中获得接近 3.3 的值,但只想将其格式化为“3.3”以供显示,那么在准备输出时,只需使用语言的数字格式化功能即可。
0赞 Simone Conti 4/9/2019
我解决了在将值作为返回值传递之前将值转换为字符串的问题

答: 暂无答案