舍入后的浮点数全部为小数

时间:2019-04-08 11:16:25

标签: rounding floating-accuracy wordpress-rest-api

我有一个休息端点,该端点返回一些简单的统计信息:总投票,平均投票,...

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)

怎么了?

0 个答案:

没有答案