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

使用FirebaseRecyclerAdapter时RecyclerView无法获取带小数的Double数据

问题解决:FirebaseRecyclerAdapter获取Double丢失小数部分

问题根源

  • 实体类Setter参数类型错误:UserDrive类中的setOvScore方法参数为int类型,Firebase反序列化时会将存储的double值强制转换为整数,直接截断小数部分,导致获取到的数据均为xx.0格式。
  • 字符串转换未做格式化处理:即使数据正确获取,直接用String.valueOf()转换double值时,不会自动保留两位小数,无法满足显示需求。

修复步骤

1. 修正UserDrive类的setOvScore方法

将setOvScore的参数类型从int改为double,保证Firebase能正确反序列化double类型数据:

public void setOvScore(double ovScore){
    this.ovScore=ovScore;
}

2. 在Adapter中格式化输出两位小数

在onBindViewHolder方法中,通过格式化工具将double值转为带两位小数的字符串:

方式一:使用DecimalFormat

// 可将DecimalFormat定义为Adapter成员变量,避免重复创建实例
DecimalFormat decimalFormat = new DecimalFormat("#.00");

// 替换原setText与日志输出代码
holder.adptr_ovScore.setText(decimalFormat.format(model.getOvScore()));
Log.i("OvScore", decimalFormat.format(model.getOvScore()));

方式二:使用String.format

holder.adptr_ovScore.setText(String.format("%.2f", model.getOvScore()));
Log.i("OvScore", String.format("%.2f", model.getOvScore()));

额外检查

若其他double类型字段(如distance、manualDistractionScore等)也出现相同问题,检查对应Setter方法是否存在参数类型错误,确保所有double字段的Setter参数均为double类型。

内容的提问来源于stack exchange,提问作者Ed Mark David

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 10:05:22