2

For example, I am trying to save the number 1.86 in CloudFirestore, but the number 1.8600000143051147 appears in the console. Is this a normal mechanism or am I making a mistake?

In application:

In application

In Console:

In console

Code:

String name = selectedProduct.getName();
float carbohydrates = Float.parseFloat(textViewCarbohydratesSaveProduct.getText().toString().split("\\ ")[1]);
float protein = Float.parseFloat(textViewProteinSaveProduct.getText().toString().split("\\ ")[1]);
float fat = Float.parseFloat(textViewFatSaveProduct.getText().toString().split("\\ ")[1]);
float weight = Float.parseFloat(editTextCurrentWeightSaveProduct.getText().toString());
float calories = Float.parseFloat(textViewCaloriesSaveProduct.getText().toString().split("\\ ")[1]);

Product newProduct = new Product(name, carbohydrates, protein, fat, weight, calories);

firebaseFirestore.collection("Users").document(currentUser)
        .collection("Type of Meal").document(typeOfMeal)
        .collection("Date of breakfast").document(date).set(newProduct);
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Lukasso777
  • 55
  • 4

2 Answers2

2

According to the documentation, Firestore's floating point type is 64-bit double precision, IEEE 754. This format has imprecision due to rounding. There is no "decimal" or "float" format in Firestore as you will find with other databases.

So basically you could rely on your app code to round the float values OR you could use strings or integers instead and parse them. For example you could store 1.90 as 190 and then convert it to 1.90 in your app code. I suggest 2nd approach, since it's easier and more common in practice.

Sergey Emeliyanov
  • 5,158
  • 6
  • 29
  • 52
1

you could use this method that returns the value of the given float number rounded to 2 decimals.

private float roundTo2Decs(float value) {
            BigDecimal bd = new BigDecimal(value);
            bd = bd.setScale(2, RoundingMode.HALF_UP);
            return bd.floatValue();
        }