提问人:Simone Conti 提问时间:4/8/2019 更新时间:4/8/2019 访问量:182
四舍五入的浮点数返回所有小数
Rounded float is returned with all decimals
问:
我有一个 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)
怎么了?
答: 暂无答案
上一个:浮点数学坏了吗?
下一个:从栅格文件获取坐标时避免倒圆角
评论
round
round(x, n)
x
n
round(…, 1)
round