How to convert a text into double in Android - java

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
}
});

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

How to get a value from an EditText field and store it in a double variable?

Here is my code first:
public class MainActivity extends AppCompatActivity
{
Spinner dropdown;
EditText e1; //user enters the bill amount before tip here
TextView tipped; //total tipped amount
TextView Bill; //the total amount of the bill including tax
String sdropdown;
double originalBill = 0; //amount that the user enters converted to a double
double result = 0; //result of multiplying bill and tax
String test1; //editText field has to be converted to a string value first
NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(); //currency format object
//Create array of items
String tip [] = {"10%", "15%", "20%", "25%", "30%"};
//Create ArrayAdaptor
ArrayAdapter<String> adaptorTipAmount;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Create the element
dropdown = (Spinner) findViewById(R.id.tipAmount);
tipped = (TextView) findViewById(R.id.tipTotal);
Bill = (TextView) findViewById(R.id.billTotal);
e1 = (EditText) findViewById(R.id.billAmount);
tipped.setText(currencyFormat.format(0));
Bill.setText(currencyFormat.format(0));
//initialize and set adaptor
adaptorTipAmount = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, tip);
adaptorTipAmount.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dropdown.setAdapter(adaptorTipAmount);
dropdown.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapter, View v,
int position, long id) {
// On selecting a spinner item
sdropdown = adapter.getItemAtPosition(position).toString();
//what editText field is initially stored in
test1 = e1.getText().toString();
//test1 string variable gets converted to a double
//originalBill = Double.parseDouble(test1);
//determines the tip amount and does the calculation based on the tip
/* if (sdropdown.equals("10%"))
{
result = originalBill * .10;
tipped.setText(Double.toString(result));
}
else if (sdropdown.equals("15%"))
{
result = originalBill * .15;
tipped.setText(Double.toString(result));
}
else if (sdropdown.equals("20%"))
{
result = originalBill * .20;
tipped.setText(Double.toString(result));
}
else if (sdropdown.equals("25%"))
{
result = originalBill * .25;
tipped.setText(Double.toString(result));
}
else if (sdropdown.equals("30%"))
{
result = originalBill * .30;
tipped.setText(Double.toString(result));
}
*/
tipped.setText("The tipped amount is: " + test1);
}
#Override
public void onNothingSelected(AdapterView<?> arg0)
{
// TODO Auto-generated method stub
}
});
}
}
The issue I'm having is whenever I try to get the value from the EditText field and store it in a double the app crashes. I've searched around for solutions to this and have found that if you store the field in a string first and then convert it to a double that would work....well it did not. I'm pretty certain that this is my error although i'm out of ideas on how to solve. I don't want to use a button either. Any help? Thanks
Try this:
How about use toString() at the end of:
tipped.setText(currencyFormat.format(0)).toString();
Hope it Helps.
First off you need to understand the difference between the two types. double is a primitive type whereas Double is an Object. In your global variable: Double originalBill;
//what editText field is initially stored in
test1 = String.valueOf(e1.getText().toString()); //clear any chance if no string in editText
//test1 string variable gets converted to a double
if(test1 != null)
originalBill = Double.parseDouble(test1);
You may need to clean up the String you get from the EditText. Use trim() to remove any whitespace, if any.
//what editText field is initially stored in
test1 = e1.getText().toString().trim();
Have a look at what value is stored in the String
Log.v("parseDouble", "test1 = " + test1);
Ensure it isn't empty, if it is make it "0"
if (test1.isEmpty()) test1 = "0";
//test1 string variable gets converted to a double
originalBill = Double.parseDouble(test1);

How to pass double value to a textview in Android? (I'm new)

I'm using EditText to store an input as a double, then using CheckBox to modify the value and store it in the variable "output". I want to display the value of "output" in a TextView when the calculate button is clicked.
Code
public class Cooking extends AppCompatActivity {
public void calculate(View view) {
EditText userInput = (EditText) findViewById(R.id.user_input);
String numString = userInput.getText().toString();
double num = new Double(numString).doubleValue();
CheckBox ozCheckBox = (CheckBox)findViewById(R.id.oz);
boolean ozInput = ozCheckBox.isChecked();
CheckBox gCheckBox = (CheckBox)findViewById(R.id.g);
boolean gInput = gCheckBox.isChecked();
if(ozInput == true) {
double output = num*28.3495;
} else {
double output = num;
}
}
Assuming you have a textView object
TextView textView = (TextView)findViewById( R.id.myTextView );
String has a method valueOf() that is pretty handy...
double d = 8008135;
textView.setText( String.valueOf( d ) );
You could even just prepend an empty String to it...
textView.setText( "" + d );
Both would give an output of
8008135.0
Here is the guide how to do it
double number = -895.25;
String numberAsString = new Double(number).toString();
textview.setText(numberAsString);
double number = 15.62;
String numberStr = Double.toString(number);
textview.setText(numberStr);

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);

how to return number values based on different user input in android

I am trying to create an application that returns a score based on user input.
for example if the user has 1000 posts on a specific site it would return 1. i would end it at 10000.
1000 = 1
2000 = 2 etc.
here is what i have so far and thanks. this site is awesome.
for now i just have each entry adding. value1+value2 etc.
public class DataIn extends Activity {
EditText editPostCount;
EditText editThanksCount;
EditText editRomCount;
EditText editThemeCount;
EditText editKernelCount;
EditText editTutorialCount;
EditText editYearsJoined;
Button mButton;
TextView results;
Button mButton1;
#Override
public void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.data_in);
android.app.ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
editPostCount = (EditText)findViewById(R.id.editPostCount);
editThanksCount = (EditText)findViewById(R.id.editThanksCount);
editRomCount = (EditText)findViewById(R.id.editRomThreads);
results = (TextView)findViewById(R.id.results);
editThemeCount = (EditText)findViewById(R.id.editThemeCount);
editKernelCount = (EditText)findViewById(R.id.editKernelCount);
editTutorialCount = (EditText)findViewById(R.id.editTutorialCount);
editYearsJoined = (EditText)findViewById(R.id.editYearsJoined);
mButton = (Button)findViewById(R.id.results_button);
mButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//When the button is clicked, call the calucate method.
calculate();
}
});
private void calculate() {
try {
Double value1 = Double.parseDouble(editPostCount.getText().toString());
Double value2 = Double.parseDouble(editThanksCount.getText().toString());
Double value3 = Double.parseDouble(editRomCount.getText().toString());
Double value4 = Double.parseDouble(editKernelCount.getText().toString());
Double value5 = Double.parseDouble(editThemeCount.getText().toString());
Double value6 = Double.parseDouble(editYearsJoined.getText().toString());
Double value7 = Double.parseDouble(editTutorialCount.getText().toString());
//do the calculation
Double calculatedValue = (value1+value2+value3+value4+value5+value6+value7);
//set the value to the textView, to display on screen.
results.setText(calculatedValue.toString());
} catch (NumberFormatException e) {
// EditText EtPotential does not contain a valid double
}
mButton1 = (Button)findViewById(R.id.clear_button);
mButton1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
editPostCount.setText("");
editThanksCount.setText("");
editRomCount.setText("");
editThemeCount.setText("");
editKernelCount.setText("");
editTutorialCount.setText("");
editYearsJoined.setText("");
results.setText("");}
});
} }
You can get the score for every value using a simple division, that is cut to an integer.
In this example I also defined one constant to determine for each different value a specific score factor.
private static final int TOTALCOUNT_SCOREFACTOR = 1000;
int totalCountScore = totalCount / TOTALCOUNT_SCOREFACTOR;
I suggest you not to use doubles, generally int is enough.
I also suggest you to use an array of values, instead of defining all of them separately. In that way, you can easily add or remove values in future.
I hope I am not misunderstanding your question, but if you want the score to add 1 point for every 1000 posts, you simply get the number of posts and divide by 1000. for example:
//value1 is the post count
int calculatedvalue = value1/1000;
So if the number of posts(value1) is 3500, calculatedvalue would be 3.(the remainder is cut off during division)

Categories

Resources