2015-05-03 17 views
-2

我想將我的兩個答案text1和text2轉換爲十進制格式。這怎麼可能?如何在Java(Android Studio)中將整數轉換爲十進制格式?

int number1, number2, answer, answer2; 
EditText edit1 = (EditText)findViewById(R.id.aNum); 
EditText edit2 = (EditText)findViewById(R.id.bNum); 
TextView text1 = (TextView)findViewById(R.id.answerNum); 
TextView text2 = (TextView)findViewById(R.id.answerNum2); 
number1 = Integer.parseInt(edit1.getText().toString()); 
number2 = Integer.parseInt(edit2.getText().toString()); 
answer = (number2/(number1 * 1000)) * 60; 
answer2 = answer/60; 
text1.setText(Integer.toString(answer)); 
text2.setText(Integer.toString(answer2)); 
+0

呀,你究竟做了同樣的方式:'Float.parseFloat' – Dici

+0

究竟你十進制格式是什麼意思? – Vincent

+0

我試過了,但是我得到錯誤「Incompatible types。Required:int Found:float」 – Alex

回答

0

您可以使用BigDecimal

即:

new BigDecimal(theInputString); 
+0

爲什麼在這裏使用'BigDecimal'?他從來沒有提到溢出的可能性...... – Dici

1

的第一個問題是整數全是數字,也就是沒有小數位,所以如果你有:

int a = 3; 
int b = 2; 
int result = a/b; 

結果將是1而不是1.5。如果您需要保留浮點值,則將它們轉換爲double或float。然後,您可以使用String.format正確顯示該值:

text1.setText(String.format("%.2f",answer)); 

這將顯示答案到小數點後兩位。

0

使用float變量類型,而不是int和float而不是Integer類類:

float number1, number2, answer, answer2 
EditText edit1 = (EditText)findViewById(R.id.aNum); 
EditText edit2 = (EditText)findViewById(R.id.bNum); 
TextView text1 = (TextView)findViewById(R.id.answerNum); 
TextView text2 = (TextView)findViewById(R.id.answerNum2); 
number1 = Float.parseFloat(edit1.getText().toString()); 
number2 = Float.parseFloat(edit1.getText().toString()); 
answer = (number2/(number1 * 1000)) * 60; 
answer2 = answer/60; 
text1.setText(Float.toString(answer)); 
text2.setText(Float.toString(answer2)); 
相關問題