sql float精度问题

时间:2016-10-20 02:14:58

标签: sql apache-spark precision

我有一个像这样的表fruit_df_sql

     +------+------------+
     | fruit|fruit_number|
     +------+------------+
     | apple|          20|
     |orange|          33|
     |  pear|          27|
     | melon|          31|
     |  plum|           8|
     |banana|           4|
     +------+------------+

我想生成每一行的百分比,但当我总结百分比列时,我无法获得100%

    select fruit, round(fruit_number/123*100,2) as cnt_percent 
    from fruit_df_sql
    order by cnt_percent desc

如果我总结cnt_percent的列,我就得到了这个

    +----------------+
    |sum(cnt_percent)|
    +----------------+
    |           99.99|
    +----------------+

不是100%。我认为这是因为划分和圆形带来浮动精度问题。请帮忙。感谢。

1 个答案:

答案 0 :(得分:0)

尝试将四舍五入为0位小数。

select fruit, round(fruit_number/123*100,0) as cnt_percent 
from fruit_df_sql
order by cnt_percent desc;