Home > Net >  Firestore doesn't read decimal point
Firestore doesn't read decimal point

Time:12-12

I want to sum the "quantity" values ​​of all files, but the decimal point is not read, only the integer is added, why is this?

enter image description here

 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? Int{
                                    self.totalVotes  = quantity
                                    self.new.text = "\(self.totalVotes)"
                                        
                                    
                                }
                            }
                }
            }
        }
    }

Here's my current function that sums integers fine, values ​​with decimal points don't read.

CodePudding user response:

values ​​with decimal points don't read

That is happening because you're casting a decimal number field type to an Int rather than to double:

if let quantity = document.data()["quantity"] as? Int

Int is a type of number that doesn't store decimal numbers. So to solve this you have to cast the value that you're reading from Firestore into a double like this:

if let quantity = document.data()["quantity"] as? Double
//                                                            
  • Related