【问题标题】:Cloud Firestore saves the number with unnecessary decimal places [duplicate]Cloud Firestore 使用不必要的小数位保存数字 [重复]
【发布时间】:2019-12-02 12:23:06
【问题描述】:

例如,我试图将数字 1.86 保存在 CloudFirestore 中,但数字 1.8600000143051147 出现在控制台中。这是正常机制还是我犯了错误?

在应用中:

在控制台中:

代码:

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);

【问题讨论】:

    标签: java android firebase google-cloud-firestore


    【解决方案1】:

    根据documentation,Firestore 的浮点类型 是 64 位双精度,IEEE 754。这种格式有imprecision due to rounding。 Firestore 中没有您在其他数据库中发现的“十进制”或“浮点”格式。

    所以基本上你可以依靠你的应用程序代码来四舍五入浮点值,或者你可以使用字符串或整数来解析它们。例如,您可以将 1.90 存储为 190,然后在您的应用代码中将其转换为 1.90。 我建议第二种方法,因为它在实践中更容易且更常见。

    【讨论】:

      【解决方案2】:

      您可以使用此方法返回四舍五入到小数点后 2 位的给定浮点数的值。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-05-06
        • 2021-08-31
        • 2018-08-15
        • 1970-01-01
        • 2021-03-26
        • 2020-06-16
        • 2016-07-08
        • 1970-01-01
        相关资源
        最近更新 更多