2

I would like to store/retrieve doubles in Firebase but if I store a whole number like 5.0, Firebase will drop the 0 and upon retrieval, I get an illegal cast from long to double. One solution would be to store and parse floating point values from strings but Firebase says it will support double type so I'd prefer to use it if possible.

double val = 1.0;
dbref.child(child).setValue(val); // '.0' dropped in db

double count = (double)dataSnapshot.child(child).getValue(); //illegal cast from long to double
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
Dan Arrick
  • 85
  • 8

2 Answers2

2

You can ask the SDK to convert it to a specific type:

double value = dataSnapshot.child(child).getValue(Double.class);

However, this will crash if the field isn't found, so you might want to check if it exists before trying to convert it:

if (dataSnapshot.child(child).exists()) {
    double value = dataSnapshot.child(child).getValue(Double.class);
}
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
0

This is because firebase basically stores numbers as either long or a double in firebase-realtime-database. If the number is an integer(not the datatype), it will be stored as a Long otherwise, it will be stored as a Double. Read more

To overcome this issue,

double count = 0.0;
try{
    // stored data is exactly a double
    count = (double)dataSnapshot.child(child).getValue();
} catch (Exception ex) {
    // stored data is exactly an integer
    count = (double)((long)dataSnapshot.child(child).getValue());
}

Hope this helps!

Lakshan Dissanayake
  • 521
  • 1
  • 4
  • 18