我有一个sqlite表,其数量字段的值为NUMERIC(10,5)(我知道数据类型在sqlite中意义不大)。我想写一个select语句,显示2位小数。
id name type notnull dflt_value pk
------- --------------- ---------- ----------- -------------- ---
0 _id integer 0 1
1 name varchar 1 0
2 amount NUMERIC(10,5) 0 0
SELECT _id, name, amount FROM accounts
是否可以在select语句中转换两位小数的数量,因此我可以在应用程序中显示两位小数。 我需要在select语句中格式化,不想更改表结构。提前谢谢。
我使用以下代码填充android
中的列表视图 cursor = dbAdapter.getAccountsTotals();
startManagingCursor(cursor);
String[] from = new String[] { DbAdapter.KEY_ID, DbAdapter.KEY_NAME, DbAdapter.KEY_AMOUNT};
int[] to = new int[] { R.id.dis1, R.id.dis2, R.id.dis3};
SimpleCursorAdapter trans = new SimpleCursorAdapter(this, R.layout.accts_row, cursor, from, to);
setListAdapter(trans);
因此在从数据库中获取后无法格式化结果。请让我知道有一种方法可以在上面的代码中分配格式化值,谢谢。
答案 0 :(得分:4)
SELECT _id, name, ROUND(amount,2) FROM accounts
以下代码会告诉您如何做到这一点
public class TestListView extends ListActivity { ... private DecimalFormat myCustDecFormatter = new DecimalFormat("########.00"); ... ... /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { ... ... ... } private void fillData() { /* Get all of the rows from the database and create the item list */ /* for mult accts, pass in acct name? */ mEntryCursor = mDbHelper.fetchAllEntries(); startManagingCursor(mEntryCursor); // Create an array to specify the fields we want to display in the list (only TITLE) String[] from = new String[]{myDbAdapter.KEY_NMBR,myDbAdapter.KEY_DATE,myDbAdapter.KEY_DESCR,myDbAdapter.KEY_AMT}; // and an array of the fields we want to bind those fields to (in this case just text1) int[] to = new int[]{R.id.txtnmbr, R.id.txtdate, R.id.txtdescr, R.id.txtamt}; // Now create a simple cursor adapter and set it to display setListAdapter(new SimpleCursorAdapter(this, R.layout.entryrow, mEntryCursor, from, to) { @Override public void setViewText(TextView v, String text) { super.setViewText(v, convText(v, text)); } }); } private String convText(TextView v, String text) { switch (v.getId()) { case R.id.txtamt: double dblAmt; //dblAmt = Double.valueOf(text); dblAmt = mEntryCursor.getDouble(AMT_COLUMN); return myCustDecFormatter.format(dblAmt); } return text; } }//end TestListView
答案 1 :(得分:2)
将float值保留为数据库中的浮点值,并在表示层中保留格式,如下所示:
float f = 1.23456f;
NumberFormat instance = NumberFormat.getInstance();
instance.setMaximumFractionDigits(2);
System.out.println(instance.format(f));