0

I'm just starting to play around with android app. I have an text field to input numbers but somehow I can only type in regular integers without decimals.

any idea what I can do so I can input decimals too?

This is what I have..

public void onClick(View arg0) {
          EditText edit = (EditText)findViewById(R.id.editText1);
          TextView text = (TextView)findViewById(R.id.textView1);
          String input = edit.getText().toString();
          float num = 0;
          try {
             num = Integer.parseInt(input);
          } catch (NumberFormatException e) {
             input = "0";
          }

          double newNum = num * 1.12;
          DecimalFormat df = new DecimalFormat("###.##");
          text.setText(input + " * 12% = " + df.format(newNum));
4

2 回答 2

8

将以下属性添加到您的EditTextin xml:

android:inputType="numberDecimal"

这将通知键盘输入小数。

于 2013-10-11T03:12:29.903 回答
4

如果你想获得十进制数字键盘,你应该在xml 文件中添加inputType值:numberDecimalEditText

android:inputType="numberDecimal"

如果你也想使用逗号和点,你也应该digitsEditTextxml 中添加:

android:digits="0123456789.,"

当你在 Java 中得到这个结果时,不要忘记用逗号替换点,因为 Double 和 Float 只能解析点分隔的文本:

String test = "12,34";
String changed = test.replace(",",".")
float value = Float.parseFloat(changed)
于 2017-08-01T17:26:58.117 回答