如何在Android Studio中显示Firestore数据库的小数数值?
解决Firestore数值字段小数部分不显示的问题
问题根源
你当前代码中使用documentSnapshot.getLong("Points")读取字段值,Long是整数类型,会直接截断小数部分,导致只显示整数。而Firestore中存储的是带小数的数值,需要用浮点类型(Double)读取,再配合格式化工具展示完整数值。
修改步骤
- 正确读取浮点数值:将
getLong替换为getDouble,获取完整的带小数的数值 - 格式化数值显示:使用
DecimalFormat对数值进行格式化,保留指定小数位数
修改后的核心代码片段
docref.addSnapshotListener(this, (documentSnapshot, error) -> { if (documentSnapshot != null && documentSnapshot.exists()) { // 读取Double类型的Points字段 Double points = documentSnapshot.getDouble("Points"); if (points != null) { // 创建格式化器,保留两位小数,支持千分位分隔(可选) DecimalFormat df = new DecimalFormat("#,###.##"); // 格式化后设置到TextView powents.setText(df.format(points)); } } });
完整修改后的MainActivity代码
import android.os.Bundle; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.FirebaseFirestore; import com.journeyapps.barcodescanner.BarcodeEncoder; import java.text.DecimalFormat; import java.util.Objects; public class MainActivity extends AppCompatActivity { private TextView powents; FirebaseFirestore fStore; FirebaseAuth fAuth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button logout = findViewById(R.id.logout); ImageView qrimage = findViewById(R.id.qrimage); powents = findViewById(R.id.powents); fStore = FirebaseFirestore.getInstance(); fAuth = FirebaseAuth.getInstance(); FirebaseUser user = fAuth.getCurrentUser(); if (user != null) { String mail = user.getEmail(); DocumentReference docref = fStore.collection("Users").document(mail); docref.addSnapshotListener(this, (documentSnapshot, error) -> { if (documentSnapshot != null && documentSnapshot.exists()) { Double points = documentSnapshot.getDouble("Points"); if (points != null) { DecimalFormat df = new DecimalFormat("#,###.##"); powents.setText(df.format(points)); } } }); } try { BarcodeEncoder barcode = new BarcodeEncoder(); Bitmap bitmap = barcode.encodeBitmap(Objects.requireNonNull(FirebaseAuth.getInstance().getCurrentUser()).getEmail(), com.google.zxing.BarcodeFormat.QR_CODE, 650, 650); qrimage.setImageBitmap(bitmap); } catch (Exception e) { e.printStackTrace(); } logout.setOnClickListener(view -> { FirebaseAuth.getInstance().signOut(); Toast.makeText(MainActivity.this, "Logged Out!", Toast.LENGTH_SHORT).show(); startActivity(new Intent(MainActivity.this, Login.class)); finish(); }); } }
格式说明
- 如果不需要千分位分隔符,可将格式化规则改为
"#.##",仅保留两位小数 - 代码中增加了空值判断,避免因文档不存在或字段为空导致的空指针异常
内容的提问来源于stack exchange,提问作者Kersey
相关产品推荐
相关产品推荐

