'Swift saving decimal to firebase

I am trying to get my numbers as accurate as possible when the user enters the information for fuel purchased. I also would like it so in the example below a user can just enter "84" for the gallons.

  • Gallons = 84.000
  • Cost per gallon = 5.199
  • Total cost = 436.72

I have it so the numbers display correctly but can't figure out how to save it to firebase.

class AddFuelViewModel: ObservableObject {
    private let repo: RepositoryProtocol
    
    var cost: String = ""
    var total: String = ""
    var gallons: String = ""
    
    @Published var saved: Bool = false
    
    init(repo: RepositoryProtocol) {
        self.repo = repo
    }
    
    func addFuel() {
        let fuel = Fuel(cost: Decimal(Int(actualCost) ?? 0),
                        total: Decimal(Int(actualTotal) ?? 0),
                        gallons: Decimal(Int(gallons) ?? 0))
        
        repo.addFuel(fuel: fuel) { result in
            switch result {
            case .success(let savedFuel):
                DispatchQueue.main.async {
                    self.saved = savedFuel == nil ? false : true
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
}

I know this isn't correct but haven't been able to find the correct way.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source