wrong calculation with double - android

I am working on a simple app, actually my first attempt in Android.
Expected result
I need the result to be shown in the English Language only, in case the mobile language is in Hindi for example.
I want the number to be shown without the letter (E) when the number is long.
Code
protected void operation(char ope){
double num1 = Double.parseDouble(txtNum1.getText().toString());
double num2 = Double.parseDouble(txtNum2.getText().toString());
double resultMulti = 0;
switch (ope) {
case '*':
resultMulti = num1 * num2;
long a3=(long)resultMulti;
if (resultMulti-a3 <= 0)
txtMultiResult.setText(a3 + "");
else
txtMultiResult.setText(String.format("%.2f",resultMulti));// without E but will be converted to Mobile Language
// txtMultiResult.setText(resultMulti+""); // with E
// txtMultiResult.setText(String.valueOf(resultMulti));// With E
// txtMultiResult.setText(Double.toString(resultMulti));// with E
imm.hideSoftInputFromWindow(btnMulti.getWindowToken(),0);
break;
}
}

How about using Locale.ENGLISH inside String.format()? As in like the following:
txtMultiResult.setText(String.format(Locale.ENGLISH, "%.2f", resultMulti));

Related

how to add 1 decimal place to score system

Im trying to make the score of my inspection have 1 decimal place so i can have more precise answer.
result = (TextView) findViewById(R.id.displaym1score);
sum=0;
total=0;
box1 = (CheckBox) findViewById(R.id.box1);
box1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (box1.isChecked()) {
sum += 1; int total = 100*sum/37;
result.setText(total + "%");
}
else {
sum -= 1; int total = 100*sum/37;
result.setText(total + "%");
}
}
});
each box you check it updates instantly and the score just needs to have a decimal place like "72.1%" instead of "72%". there is also 36 more boxes set up the same way.
Ive tried a few things and i cannot figure it out. what do i do?
First total must be a float or a double, not int
instead setText( ... put:
result.setText(String.format("%.1f", total) + "%"); // 1 is the decimal places you want
Probably the easiest way is to use a double instead of an int then format the output to display one decimal place.
use double for total and use following method to get your answer.
public double getFormattedTotal(double total){
DecimalFormat precision = new DecimalFormat("0.0");
return precision.format(total);
}

Invalid Int "+" happens with any numerical operator

I am taking a crack at Android development and for my first app.. pun intended, I decided to go with a calculator. So my problem is that any arithmetic operator is evaluated as a numeric datatype and crashes the app. I've seen this discussed on other forums but most of them where syntactical issues, and I don't see that here.
Anyway here is my code any help is appreciated.
public void btnEqual_Click(View v){
TextView tv = (TextView)findViewById(R.id.txtInput);
TextView tv2 = (TextView)findViewById(R.id.txtOutput);
String s = tv.getText().toString();
Integer first;
Integer second;
Number result;
Integer x;
for(Integer i = 0; i <= s.length() - 1 ; i++){
switch(s.charAt(i))
{
case '/': x = s.indexOf("/");
first = Integer.valueOf(s.substring(0, x));
second = Integer.valueOf(s.substring(x+1, s.length()));
result = first / second;
tv2.setText(result.toString());
break;
case '*': x = s.indexOf("*");
first = Integer.valueOf(s.substring(0, x));
second = Integer.valueOf(s.substring(x+1, s.length()));
result = first * second;
tv2.setText(result.toString());
break;
case '-': x = s.indexOf("-");
first = Integer.valueOf(s.substring(0, x));
second = Integer.valueOf(s.substring(x+1, s.length()));
result = first - second;
tv2.setText(result.toString());
break;
case '+': x = s.indexOf("+");
first = Integer.valueOf(s.substring(0, x));
second = Integer.valueOf(s.substring(x+1, s.length()));
result = first + second;
tv2.setText(result.toString());
break;
default: break;
}
if(!tv2.getText().toString().isEmpty()){break;}
}
Here is the error I'm getting
Caused by: java.lang.NumberFormatException: Invalid int: "+"
You have to use x+1 in your substring, to cut the operator sign from the numerical value:
Integer.valueOf(s.substring(x+1, s.length() - 1));

Unable to make backspace button function

I am adding a backspace button in my calculator app and it is working fine also. The problem is, by default, my calculator is taking digits from decimal part i.e. initially it is 0.00, when I input 1 it becomes 0.01,when I input 2 it becomes 0.12 and so on and so forth. Now, when I press backspace it is deleting 2 and showing 0.01 but if I press 3 instead of showing 0.13 it shows 1.23. How to resolve this?
Code for the backspace button:-
private String addCurrency(String digits) {
String string = ""; // Your currency
enteredNumber = enteredNumber + digits;
// Amount length greater than 2 means we need to add a decimal point
if (enteredNumber.length() > 2) {
String rupee = enteredNumber.substring(0,
enteredNumber.length() - 2); // Pound part
String paise = enteredNumber.substring(enteredNumber.length() - 2); // Pence
// part
if (enteredNumber.contains(".")) {
}
string += rupee + "." + paise;
} else if (enteredNumber.length() == 1) {
string += "0.0" + enteredNumber;
Log.d("TextWatcher", "length 1 " + string);
} else if (enteredNumber.length() == 2) {
string += "0." + enteredNumber;
Log.d("TextWatcher", "length 2 " + string);
}
return string;
}
WHERE:-
enteredNumber is just a String type variable.
If you wish to show your numbers with two decimal points all the time, then why so much trouble? Use this -
public void getMyNumber(String yourInputNumber){
Double result = Integer.ParseInt(yourInputNumber)/100;
private static DecimalFormat REAL_FORMATTER = new DecimalFormat("0.##");
textview1.setText(REAL_FORMATTER.format(result));
}

Android - Program crashes when there is not input in editText fields

So i'm having a problem in my code which is probably simple to solve but its my first app so cut me some slack. When I enter no values in my editText box my app crashes. Im semi aware why it occurs but I cant seem to solve it.
public void onButtonClick( View v)
{
Double n1 , n2 , answer1;
EditText e1 = (EditText) findViewById(R.id.num1);
EditText e2 = (EditText) findViewById(R.id.num2);
TextView t1 = (TextView) findViewById(R.id.answer);
n1 = Double.parseDouble(e1.getText().toString());
n2 = Double.parseDouble(e2.getText().toString());
if (n1.toString().length()< 0 || n2.toString().length()< 0){
t1.setText("Please enter a number into both the base and height");
}else {
answer1 = ((n1 * n2) / 2);
t1.setText(Double.toString(answer1));
}
}
First check if there is input in both EditTexts and only if there is convert it to Double:
if (e1.getText().length() == 0 || e2.getText().length() == 0) {
t1.setText("Please enter a number into both the base and height");
} else {
n1 = Double.parseDouble(e1.getText().toString());
n2 = Double.parseDouble(e2.getText().toString());
answer1 = ((n1 * n2) / 2);
t1.setText(Double.toString(answer1));
}
EditText.getText() will never return null (as per source code) so it's safe to use methods on it (such as length().
if (!e1.getText().toString().isEmpty()) {
// do stuff
}

unable to parse "" as integer[FC]

I have this code to control if a EditTextPreference is null or not:
case R.id.prochain_vidange:
settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String choix_huile = settings.getString("listPref_huile_moteur", "0");
km = settings.getString("km", "");
Log.d("TAG",km);
int x= Integer.valueOf(km);
if (km != "")
{
if (Integer.valueOf(choix_huile) == 0) {
............
The problem is in this line:
int x= Integer.valueOf(km);
What could be the problem ?
Thanks.
If you give Integer.valueOf(String s) a string that is not a valid number, it throws a NumberFormatException. Change the default value to 0:
km = settings.getString("km", "0");
Alternatively, you can catch the exception, and set x to 0:
km = settings.getString("km", "");
int x;
try {
x = Integer.valueOf(km);
} catch(NumberFormatException e) {
x = 0;
}
Integer.valueOf trys to make a new Integer with .parseInteger(String s), "" cant be parsed to a valid number so you get a NumberFormatException
You can catch it with a try catch block or you can simply dont try to make a Integer with the String "".
before:
int x= Integer.valueOf(km);
if (km != "") {
after:
if (km != "") {
int x= Integer.valueOf(km);
Integer.valueOf(km) can throw an exception if the the km string is not able to be parsed as an integer.
However, wrapping it in a try { } catch() block is not an approach I would recommend.
The whole purpose of having a default value on the getString() method in SharedPreferences is that there can be a default value to fall back on if the preference doesn't exist. So the better way to solve this is to modify your settings.getString(...) call to be like this:
km = settings.getString("km", "0");
Then your subsequent call to Integer.valueOf(km) will not have a blank to fail upon.
Is the input string coming from a blank text field where the user can enter any value? If so, it's at that point that you can validate the value that the user entered. By validating the input early on, you won't need to scatter the checking/validating mechanism to other areas of your code.

Categories

Resources