Round to 2 decimals and pass through TextView - java

want to make generic dividing app just to test some stuff out because I'm pretty new at everything still. I get the final number, I just don't know how or where to apply NumberFormat or DecimalFormat or how to properly Math.Round so I only get 2 decimal places as a result. I'll want to spit whatever number divided out back into a text view.
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
thing1 = (EditText) findViewById(R.id.thing1);
if (TextUtils.isEmpty(thing1.getText().toString())) {
n1 = 0;}
else {
n1 = Integer.parseInt(thing1.getText().toString());
}
thing2 = (EditText) findViewById(R.id.thing2);
if (TextUtils.isEmpty(thing2.getText().toString())) {
n2 = 0;}
else {
n2 = Integer.parseInt(thing2.getText().toString());
}
if (n2 !=0){
total = (n1 / n2);}
final double total = ((double)n1/(double)n2);
final TextView result= (TextView) findViewById(R.id.result);
result.setText(Double.toString(total));
}
});
}

Try using the String.format() method, it will create a string with that number rounded (up or down as appropriate) to two decimal places.
String foo = String.format("%.2f", total);
result.setText(foo);

Try using this code:
DecimalFormat df = new DecimalFormat();
DecimalFormatSymbols dfs = new DecimalFormatSymbols();
dfs.setGroupingSeparator(',');
dfs.setDecimalSeparator('.');
df.setDecimalFormatSymbols(dfs);
df.setMinimumFractionDigits(2);
df.setMaximumFractionDigits(2);
result.setText(df.format(n1 / n2));
Hoping it's work. Thanks

you can use String.format()
result.setText(String.format("%.2f", total));
OR
use Math.round()
Math.round(total*100.0)/100.0
like this:
result.setText(Double.toString(Math.round(total*100.0)/100.0));

You should try this
result.setText(String.format( "%.2f", total) );

Related

Rounding results from different java calculations

So I've got the following code which makes some calculations depending on user input and then shows the results in a textView.
public class DescentCalculator extends AppCompatActivity {
EditText num1, num2, num3;
TextView resu;
double startdecent;
double feetminute;
#Override
public void onCreate ( Bundle savedInstanceState ) {
super.onCreate(savedInstanceState);
setContentView(R.layout.descent);
Toolbar mToolbar = (Toolbar) findViewById(R.id.mtoolbar);
setSupportActionBar(mToolbar);
Button add = (Button) findViewById(R.id.button11);
num1 = (EditText) findViewById(R.id.altitude_fix);
num2 = (EditText) findViewById(R.id.altitude_cruise);
num3 = (EditText) findViewById(R.id.mach_speed);
resu = (TextView) findViewById(R.id.answer);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick ( View v ) {
// TODO Auto-generated method stub
String altfix = num1.getText().toString();
String altcruise = num2.getText().toString();
String machspeed = num3.getText().toString();
startdecent = (Double.parseDouble(altcruise) - Double.parseDouble(altfix)) / 100 / 3;
feetminute = (3 * Double.parseDouble(machspeed) * 1000);
resu.setText(Double.toString(startdecent) + Double.toString(feetminute));
}
});
}
For example, if the user enters 7000 for the altcruise, 6000 for altfix and 0.30 for machspeed the app calculates the answer as 3.33333333333335899.999999999 which is technically right. I'd like the app to round up the answer and display 3.3 in this case.
Look at this answer: Round a double to 2 decimal places
This code snippet takes in a double and reads it into a BigDecimal and rounds it returning a double with n decimalplaces.
public static void main(String[] args){
double myDouble = 3.2314112;
System.out.print(round(n,1));
}
public static double round(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}
This returns 3.2

Why are my Java percentages slightly wrong?

I'm writing a simple Percentage Calculator android app in Android Studio. Here's my psuedo:
resultView = (TextView) findViewById(R.id.ResultView);
percentageText = (EditText) findViewById(R.id.PercentageInput);
numberText = (EditText) findViewById(R.id.NumberInput);
Button calcButton = (Button) findViewById(R.id.Calculate_btn);
calcButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
if(percentageText.length() != 0 && numberText.length() != 0)
{
float percentage = Float.parseFloat(percentageText.getText().toString()) / 100;
float result = percentage * Float.parseFloat(numberText.getText().toString());
resultView.setText(Float.toString(result));
}
else if(percentageText.length() == 0 && numberText.length() == 0)
{
resultView.setText("Don't be dumb...");
}
}
});
so it seemed like everything was working fine. Simple percentages are always right. 50%100=50, 25%50=12.5 ... but then I get to 3 and 6. 3%10= 0.29999998 ... shouldn't it be .3? and 60%100= 60.000004 ... Any help out there?
It has to do with the fact that double variables have a limited number of bits. This is like saying 1/3 = 0.33333333 when really is should be equal to 0.33333333... forever!
Read about Floating points and Double precision

android EditText calculating wrong result

I was trying to make a simple APP that converts between Celsius and Fahrenheit:
I wrote two EditText, one is for input and another is for output, also I have two buttons (toC and toF).
The code is as following:
public class MainActivity extends ActionBarActivity {
private EditText EditText_input;
private EditText EditText_output;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText_input = (EditText) findViewById(R.id.input);
EditText_output = (EditText) findViewById(R.id.output);
Button toC = (Button) findViewById(R.id.c);
toC.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String inputS = EditText_input.getText().toString();
double inputD = Double.parseDouble(inputS);
double outputD = (5/9) * (inputD-32);
String outputS = String.valueOf(outputD);
//Toast.makeText(MainActivity.this,String.valueOf(outputD),Toast.LENGTH_LONG).show();
EditText_output.setText(outputS, TextView.BufferType.EDITABLE);
}
});
Button toF = (Button) findViewById(R.id.f);
toF.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
String inputS = EditText_input.getText().toString();
double inputD = Double.parseDouble(inputS);
double outputD = (9/5) * inputD + 32;
String outputS = String.valueOf(outputD);
EditText_output.setText(outputS, TextView.BufferType.EDITABLE);
}
});
}
After clicking the button toC, it always produces 0.0, and clicking the button toF would produce a wrong result. I set the inputType for the EditText as numerdecimal, I tried number but still doesn't work.
I checked that the problem is from outputD, but I have no idea why outputD can't get a correct result.
Could anyone help me?
When you calculate double outputD = (5/9) * (inputD-32); the compiler assumes that 5 and 9 are ints, so 5/9 is zero. If you want the compiler to treat the numbers as doubles, you should write double outputD = (5.0/9.0) * (inputD-32);. The same applies to the second conversion - double outputD = (9/5) * inputD + 32;
5 and 9 both are integer that is why it always give integer
so 5/9 will always give 0.
Make it
5/9.0
or 5.0/9.0
it will definately work
Compiler treats division (5/9) as a Integer division.
Hence first result is always zero.
You can make one of the number as double like 5.0 or 9.0
double outputD = (5.0/9) * (inputD-32);
Or
double outputD = (5/9.0) * (inputD-32);
Or
double outputD = (5.0/9.0) * (inputD-32);

Rounding to one decimal place

I im currently working on a temprature converter app. Everything works but I can get over 5 decimals and I have tried to look it up and search on Google but can't find out how do it. Here is where I display the text in the main.java:
text = (EditText) findViewById(R.id.editText1);
result = (TextView) findViewById(R.id.tvResult);
float inputValue = Float.parseFloat(text.getText().toString());
DecimalFormat df = new DecimalFormat("#.00");
String s = (String.valueOf(ConvertFahrCels.convertCelsiusToFahrenheit(inputValue)));
String d = (String.valueOf(ConvertFahrCels.convertFahrenheitToCelsius(inputValue)));
if (celsiusButton.isChecked()) {
result.setText(d);
celsiusButton.setChecked(false);
fahrenheitButton.setChecked(true);
} else {
result.setText(s);
fahrenheitButton.setChecked(false);
celsiusButton.setChecked(true);
}
And here is where I calculate it:
// converts to celsius
public static float convertFahrenheitToCelsius(float fahrenheit) {
return ((fahrenheit - 32) * 5 / 9);
}
// converts to fahrenheit
public static float convertCelsiusToFahrenheit(float celsius) {
return ((celsius * 9) / 5) + 32;
}
Your code here implies it is creating a decimal format to do the work, but, you don't actually use it!
DecimalFormat df = new DecimalFormat("#.00");
String s = (String.valueOf(ConvertFahrCels.convertCelsiusToFahrenheit(inputValue)));
String d = (String.valueOf(ConvertFahrCels.convertFahrenheitToCelsius(inputValue)));
The code should be:
DecimalFormat df = new DecimalFormat("#.00");
String s = df.format(ConvertFahrCels.convertCelsiusToFahrenheit(inputValue));
String d = df.format(ConvertFahrCels.convertFahrenheitToCelsius(inputValue));
It is more common in Java now to use String formatting instead of decimal format. Consider:
String s = String.format("%.1f", ConvertFahrCels.convertCelsiusToFahrenheit(inputValue));
Finally, your question indicates you want 1 decimal place, but, the Decimal format you use adds two.

How to convert a text into double in Android

I used the following way to change the string into double but unfortunately this closes the app. The EditText inputtype is "NumberDecimal"
numA = (EditText) findViewById(R.id.numA);
numB = (EditText) findViewById(R.id.numB);
//App forceclose here. Not sure why.
final Double a = Double.parseDouble(numA.getText().toString());
final Double b = Double.parseDouble(numB.getText().toString());
calculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
numLS.setText("" + ( (- (Double) b) /(2 * (Double) a)));
}
});
Try this;
String s = b.getText().toString();
final double a = Double.valueOf(s.trim()).doubleValue();
Perform this check:
if (!numA.getText().toString().equals("")) {
final Double a = Double.parseDouble(numA.getText().toString());
}
if (!numB.getText().toString().equals("")) {
final Double b = Double.parseDouble(numB.getText().toString());
}
An empty string argument to Double.parseDouble() produces a NumberFormatException.
As a suggestion, if you are working on making a calculator(or converter), you should add more checks for invalid input. For example, you should add a check for when the user inputs just the decimal point(.) or input of form (3.).
You may wish to use a try catch because other unparseable data will throw an exception and it may not be the best to rely on the UI to force valid numbers only.
numA = (EditText) findViewById(R.id.numA);
numB = (EditText) findViewById(R.id.numB);
Double a;
Double b;
try {
a = Double.parseDouble(numA.getText().toString());
b = Double.parseDouble(numB.getText().toString());
} catch (NumberFormatException e) {
e.printStackTrace();
a = 0.0;
b = 0.0;
}
final double aFin = a;
final double bFin = b;
calculate.setOnClickListener(new View.OnClickListener() {
//Also, you used your class as an onClickListener you would have to make your doubles final.
#Override
public void onClick(View v) {
numLS.setText("" + ( (- (Double) b) /(2 * (Double) a)));
//Division by zero will produce a NaN you should probably check user input data sanity
}
});

Categories

Resources