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

Firestore无法读取小数点,求和仅累加整数问题排查

问题原因

你代码里的核心问题出在类型转换逻辑上:

  • Firestore中带小数点的quantity字段存储的是浮点数(比如Double类型),但你用as? Int尝试把它转换成整数类型Int,这种转换会直接失败——带小数的字段值根本不会进入求和逻辑,自然只有整数类型的字段被累加。
修复方案
  1. 调整总和变量类型:把存储累加结果的totalVotes改成Double类型,确保能容纳浮点数的求和结果:
    var totalVotes: Double = 0
    
  2. 修正字段类型转换:将字段值转换成Double而非Int,这样就能读取带小数的数值了:
    func getDatas2(){
            
            self.db.collection("Admin").document("AI智能機器人").collection("Ai日獲利").getDocuments { snapshot, error in
                if error != nil {
                    print(error?.localizedDescription ?? "Error while getting data from server!" )
                }else{
                    if snapshot?.isEmpty != true && snapshot != nil {
                        
                        for document in snapshot!.documents{
                            
                                    if let quantity = document.data()["quantity"] as? Double{
                                        self.totalVotes += quantity
                                        // 可选:根据需求格式化显示,比如保留两位小数
                                        self.new.text = String(format: "%.2f", self.totalVotes)
                                        // 也可以直接转字符串:"\(self.totalVotes)"
                                    }
                                }
                    }
                }
            }
        }
    
  3. 兼容说明:如果Firestore中同时存在整数和浮点数类型的quantity字段,上述逻辑依然有效——整数会被自动转换为Double参与求和。

内容的提问来源于stack exchange,提问作者lin lin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 17:01:23