You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spark DataFrame cast(DecimalType)精度异常问题求助

Spark DataFrame DecimalType 精度丢失问题解决

问题根源

你遇到的精度丢失核心原因是:代码里的365.25 / 12属于Double浮点数运算——Double类型有效数字仅15-17位,计算时已经丢失部分精度,后续再用cast(DecimalType(38,20))转换也无法找回丢失的精度。而移除除法后结果正确,是因为datediff返回整数,没有浮点数运算带来的精度损耗。

解决方案

把所有参与运算的数值都转换成Decimal类型,让整个计算过程在高精度Decimal体系下执行,避免浮点数介入:

修改后的代码

avg(
    when((col("a.is_debtor") == 1) & (col("a.is_kk") == 0) & (col("a.is_open") == 0),
         datediff(col("a.date_end_plan"), col("a.date_end_fact"))
           .cast(DecimalType(38,20)) 
           .divide(lit(365.25).cast(DecimalType(38,20)).divide(lit(12).cast(DecimalType(38,20))))
    )
).cast(DecimalType(38, 20)).alias("loan_avg_plan_fact_closed_mm_cnt")

关键改动说明

  • 先将datediff的结果转为DecimalType,确保被除数是高精度类型
  • 把365.25和12都显式转为DecimalType,再执行除法得到高精度除数
  • 全程用Decimal类型执行运算,保留足够小数位,后续avg计算和最终转换就能得到预期的20位小数精度

内容的提问来源于stack exchange,提问作者Егор Бугаков

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 05:38:27