I have made an calculation, took of the decimals but now i would like to make so that it show a down rounded number. I found that i can use math.floor but i can't get it in the code. I took the decimals off but can't get it to round down.
code is like this (the part which does the math):
public void onClick(View view) {
if (etBarfles.getText().toString().equals("")) {
Toast.makeText(getActivity(), "Vul zowel bar in fles, inhoud fles als liters per " +
"minuut in!", Toast.LENGTH_SHORT).show();
} else {
if (etInhoudfles.getText().toString().equals("")) {
Toast.makeText(getActivity(), "Vul zowel bar in fles, inhoud fles als liters per " +
"minuut in!", Toast.LENGTH_SHORT).show();
} else {
if (etLitersperminuut.getText().toString().equals("")) {
Toast.makeText(getActivity(), "Vul zowel bar in fles, inhoud fles als liters " +
"per minuut in!", Toast.LENGTH_SHORT).show();
} else {
}
tvResult.setText(nodecimals((((Float.parseFloat(etBarfles.getText().toString()) *
(Float.parseFloat(etInhoudfles.getText().toString())) / (Float.parseFloat
(etLitersperminuut.getText().toString()))) / 60))));
}
}
}
private String nodecimals(float val) {
return String.format("%.0f", val);
}
Try the following
tvResult.setText(String.valueOf((int) Math.floor(((Float.parseFloat(etBarfles.getText()
.toString()) *
(Float.parseFloat(etInhoudfles.getText().toString())) / (Float.parseFloat
(etLitersperminuut.getText().toString()))) / 60))));
(int) Math.floor()
will convert the value to an integer floor value, and then String.valueOf()
will convert that int
to String
, so that you can set the same to the TextView
.
THINGS TO IMPROVE:
You can make your code better by following these guidelines:
You are using the same line etBarfles.getText().toString()
in multiple places for your check conditions. Its best if you initialize a variable with that value. Something like
String etBarFilesText = etBarfles.getText().toString();
Your condition etBarfles.getText().toString().equals("")
can be written the Android
way as follows
!TextUtils.isEmpty(etBarFilesText)
Your strings should be defined in your strings.xml
. So if your error msgd is named error_string
in the strings.xml
then your Toast
message will look something like this.
Toast.makeText(getActivity(), getString(R.string.error_string), Toast.LENGTH_SHORT).show();
Your line
tvResult.setText(nodecimals((((Float.parseFloat(etBarfles.getText().toString()) *
(Float.parseFloat(etInhoudfles.getText().toString())) / (Float.parseFloat
(etLitersperminuut.getText().toString()))) / 60))));
could have been wayy simpler, and more readable if you used different variables, instead of writing everything in a big single sentence.