Android应用中数据库读取数字去除.0后缀的问题求助
.0 for Integer Values Stored as Double Hey there! I totally get why that extra .0 showing up next to whole numbers is frustrating—you want the display to match exactly what the user input, right? Let's break down how to fix this.
The Root of the Problem
When you convert a Double that’s actually an integer (like 32453905.0) to a string using Double.toString(), Java automatically appends .0 because it treats the value as a floating-point number. We need to detect when the value is a whole number and format it accordingly.
Solution 1: Check if the Double is an Integer First
You can write a simple helper method to verify if the double has no fractional part, then format it as an integer string if it does. Here's how:
private String formatDoubleForDisplay(double number) { // Check if the double is a whole number (no decimal part) if (number == Math.floor(number) && !Double.isInfinite(number)) { // Cast to long to safely handle large integer values return String.valueOf((long) number); } else { // Keep the decimal part for non-integer values return String.valueOf(number); } }
Replace your existing display code with this:
double storedNumber = user.getNumber(); editTextNationalNumber.setText(formatDoubleForDisplay(storedNumber));
Solution 2: Use DecimalFormat for Flexible Formatting
If you want more control over decimal places for non-integer inputs, DecimalFormat is a great tool—it automatically omits the .0 for whole numbers while preserving decimals when needed:
import java.text.DecimalFormat; // Define the formatter once (as a class-level constant for efficiency) private static final DecimalFormat NUMBER_FORMATTER = new DecimalFormat("#.##"); // When displaying the number: String formattedNumber = NUMBER_FORMATTER.format(user.getNumber()); editTextNationalNumber.setText(formattedNumber);
The #.## pattern means:
- Show up to two decimal places if they exist
- Omit the decimal point entirely for whole numbers
Bonus: Adjust the Database Type (If Possible)
If your users will only ever input integer values, consider changing your database field to store the number as a Long or Integer instead of Double. This eliminates floating-point formatting issues entirely—just read the integer directly and convert it to a string normally.
Testing It Out
For your example input 32453905, both solutions will display 32453905 instead of 32453905.0. If a user inputs a decimal like 123.45, it will still show correctly as 123.45.
内容的提问来源于stack exchange,提问作者Kumar

