我有一个带有 REAL 字段表的 SQLDB。在我的布局中,我已将其字段大小设置为仅允许 8+2 位数字。在我的对象中,我将字段的数据类型用作“float”。
qs[0] = "CREATE TABLE " + RELATION_TABLE_NAME + "(id TEXT PRIMARY KEY, name TEXT NOT NULL, startBal REAL NOT NULL, currentBal REAL NOT NULL);";
<EditText android:text="" android:id="@+id/relCurrBalTxt" style="@style/EditTextStyle"
android:inputType="numberDecimal" android:maxLength="11" android:hint="12345678.99" />
我在 editText 中输入了值“87654321.99”并点击了保存。它填充对象
// Send the data to object
rowData.setValue(2, Float.parseFloat(sbalTxt.getText().toString()));
// In object, this is how I save it
this.setCurrentBalance( ((Float)value).floatValue() ); // value is Object type
// Saving data in ContenteValues to save to DB
// LOG Rcvd from Object while Saving CurrBal: 8.765432E7
values.put("currentBal", new Float(rowData.getValue(3).toString()));
保存时,它会直接显示包含更新数据的表格。在表格中显示它时,我使用 DecimalFormat 来确保它以正确的方式显示:
field_type = r.getFieldType(field);
// Get Data
str = r.getValue(field).toString();
// Format accordingly
if(field_type.equals(DBRow.DOUBLE_TYPE) || field_type.equals(DBRow.FLOAT_TYPE)) {
double douValue = Double.parseDouble(str);
//NumberFormat nf = NumberFormat.getNumberInstance(Locale.ITALY);
//DecimalFormat df = (DecimalFormat) nf;
DecimalFormat df = new DecimalFormat();
df.applyPattern("##,###,###.##");
df.setGroupingUsed(true);
str = df.format(douValue);
// Log.v("DF", "While Showing in Table : double = " + douValue + " String = " + str);
}
((TextView) tr.getChildAt(field)).setText(str);
这里显示了值:8.765432E7
当我再次选择该行以查看 EditText 中的值时,我看到:87654320.00
值是如何变化的?在其他情况下,我也将数据保存为“50009876.99”,但不知何故它不保存 .99 并将其设为 .00,即 50009876.00。
为什么事情不能正常工作?我哪里出错了?
非常感谢任何帮助。
*编辑:用于在表中显示的 DecimalFromat 代码 *
// Format accordingly
if(field_type.equals(DBRow.DOUBLE_TYPE) || field_type.equals(DBRow.FLOAT_TYPE)) {
/*
WAS USING THIS CODE TILL NOW
DecimalFormatSymbols dfs = new DecimalFormatSymbols();
String decep = String.valueOf(dfs.getDecimalSeparator());
int index = str.indexOf(decSep);
if (index > 0) {
// If digits after decimal are more than 2
if (str.substring(index+1).length() > 2) {
str = str.substring(0, index+3);
}
}
DecimalFormat df = new DecimalFormat();
df.setGroupingUsed(true);
str = df.format(Double.parseDouble(str));
if (addRow)
create_addTextView(tr, str, true);
else
((TextView) tr.getChildAt(field)).setText(str);
*/
// DECIMALFORMAT CODE
double douValue = Double.parseDouble(str);
DecimalFormat df = new DecimalFormat();
df.applyPattern("##,###,###.##");
df.setGroupingUsed(true);
str = df.format(douValue);
if (addRow)
create_addTextView(tr, str, true);
else
((TextView) tr.getChildAt(field)).setText(str);
}
最佳答案
我认为您的问题是您将数字存储为 Float
。 Float
没有很好的精度 - 它实际上只有 23 位二进制数字的精度,如 here 所示.这意味着您无法在 float
中准确存储小数点前的 7 位数字,甚至更糟 - 小数点前的 7 位数字和小数点后的几位数字。这意味着您错误地选择了余额变量的类型 - 您不能存储在 Float
8+2 中。我建议您将类型更改为 Double
,它具有更大的精度范围。
关于安卓/SQLite : Saving/Retrieving data of type REAL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9044728/