2012-05-07 218 views
0

我有一個textview,我設置從一個SimpleCursorAdapter獲得的值的文本。我的SQLite數據庫中的字段是一個實數。這裏是我的代碼:Android字符串格式化

 // Create the idno textview with background image 
     TextView idno = (TextView) view.findViewById(R.id.idno); 
     idno.setText(cursor.getString(3)); 

我的問題是文本顯示小數。值是1081,但我得到1081.0000。如何將字符串轉換爲不顯示小數?我已經看過格式化程序,但是我無法正確理解語法。

 TextView idno = (TextView) view.findViewById(R.id.idno); 
     String idno = cursor.getString(3); 
     idno.format("@f4.0"); 
     idno.setText(idno); 

感謝高級!

回答

2

您可以使用String.format

String idno = String.format("%1$.0f", cursor.getDouble(3)); 

你也DecimalFormat可以:

DecimalFormat df = new DecimalFormat("#"); 
String idno = df.format(cursor.getDouble(3)); 
+0

感謝您的回覆!它效果很好。我確實必須使用不同的變量名稱,因爲我也使用idno作爲textview。 – wyoskibum

0

如果你得到一個String帶小數點的,你可以簡單地做:

idno.setText(cursor.getString(3).split("\\.")[0]); 
//   Split where there is a point--^ ^
//           | 
//   Get the first in the array--------+ 

需要注意的是這樣的:

TextView idno = (TextView) view.findViewById(R.id.idno); 
String idno = cursor.getString(3); 

是非法的,因爲你使用相同的變量名。

+0

感謝您的答覆!我試圖運行時弄清楚重複的變量名稱。 ;-D – wyoskibum