我试图在Android Studio中将十进制数分为整数和点数
Button btSpilt;
EditText Input;
TextView wholenumber, points;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
wholenumber = (TextView) findViewById(R.id.wholenumber);
points = (TextView) findViewById(R.id.points);
Input = (EditText) findViewById(R.id.Input);
btSpilt = (Button) findViewById(R.id.btSpilt);
btSpilt = findViewById(R.id.btSpilt);
btSpilt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String s_input = Input.getText().toString();
double input = Double.parseDouble(s_input);
int a = Integer.parseInt(s_input);
double aa = a;
double b = (10 * input - 10 * input)/10;
String str_a = Integer.toString((int) aa);
String str_b = Integer.toString((int) b);
wholenumber.setText(str_a);
points.setText(str_b);
}
});
在输入整数时效果很好,但是在输入小数时整个应用程序崩溃
答案 0 :(得分:1)
Math.floor()
将帮助您:https://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#floor(double)
double input = Double.parseDouble(s_input);
double wholeNumber = Math.floor(input);
double afterDecimal = input - wholeNumber;
答案 1 :(得分:0)
int a = Integer.parseInt(s_input);//this line caused error when s_input represents decimal.
double b = (10 * input - 10 * input)/10;//b always equal zero
要获得双精度的整数和小数部分,可以尝试使用split
String s_input = Input.getText().toString();
if (s_input.contains(".")) {
String[] split = s_input.split("\\.");
String whole = split[0];
String fractional = split[1];
}