How to displaying Float/Double in meaningful form in Android - android

I am trying to make a BMI application. When I run the application the BMI values are displayed in numeral form that I don't understand. I have tried both Float and Double type but results are same.
For example:
Height (m): 2
Weight (Kg): 100
BMI is displayed as : 2.0E-4 instead of 25
The part of the code that effects this is:
String editText1= height_field.getText().toString();
String editText2= weight_field.getText().toString();
try { // Parse string to int
double height = Double.parseDouble(editText1);
double weight = Double.parseDouble(editText2);
double bmi_result = (weight/(height*height));
String bmi_text = Double.toString(bmi_result);
display.setText(bmi_text);
System.out.println("OnClick: computeButton is clicked");
}
catch(NumberFormatException nfe) {
alert.show(); // Show error alert

To answer your original question, you should be using java.text.DecimalFormat, something like:
DecimalFormat formatter = new DecimalFormat("##.##");
display.setText(formatter.format(bmi_result));
Will force the result to be in the format of two digits followed by two decimal points, the table in the link above shows how to generate that.
However, since 2.0E-4 is 0.0002, I think Jon Skeet's comment is correct: You're doing your math operation wrong, since the value you're printing is a very small fraction of 25 :)
I'd recommend using Log.v() to print out your math operation before you actually do it, so you can see what the values of weight and height actually are, I highly doubt they're correctly set at what you described in the question.

Related

Number Format Exception "Invalid Double"

I have to build a calculator and i am making some validations, the code is kinda long so i will only put the part that is breaking it.
It is a validation that makes the multiplication, it breaks when trying to multiply a negative number, every other operation is done correctly but the multiplication:
else if(resulttxt.getText().toString().contains("*")){
String resultarray=resulttxt.getText().toString();
String[] split=resultarray.split("\\*");
finalresult = Double.valueOf(split[0]) * Double.valueOf(split[1]);
if (finalresult<0){
negative=true;
}else{
negative=false;
}
resulttxt.setText(String.valueOf(finalresult));
resulttxt is received from a TextView that gets it's data from cliking on the numbers or the signs which are also TextViews (not buttons but they do have the On click listener)the operation is done when ciclking on the = sign.
This throws an error if for example i try to do -6*45:
java.lang.NumberFormatException: Invalid double: "6*45"
Like i said everything works with the addition,substraction and division it is only the multiplication that breaks.
I tried executing your code in the compiler :
String resulttxt = "-6*45";
boolean negative = false;
if(resulttxt.contains("*")){
String resultarray=resulttxt;
String[] split=resultarray.split("\\*");
double finalresult = Double.valueOf(split[0]) * Double.valueOf(split[1]);
if (finalresult<0){
negative=true;
}else{
negative=false;
}
System.out.println(finalresult);
}
Every thing worked fine for, please verify datatype used in your program.
addition, multiplication and division works fine. "-6+45, -6*45 and -6/45"(any other combination. I just used the same)
However for subtraction as the pattern is "-6-45" the above logic will fail and throw number format exception. This is because if you split "\-", the "-" is first character in string and there is nothing before it.
Thus your split will fail. So to avoid this you can always take last index of character to split using substring function.
OMG dudes... this is what was the problem:
I had this validation at the end of the other operations, so BEFORE even going to the multiplication part it entered the "-" validation when it checks
if(resulttxt.contains("-")){
because it is a negative value so it does have a "-"... so it entered as a substraction instead as a multiplication because of that...
To solve it i had to put the substraction validation at the bottom of all of them.
So thank you for the guys who suggested me to check the line where the error was thrown i wouldn't have known logcat actually tells you were the mistake is and to my surprise it was on the substraction validation which to me was a "WTF" moment and then i realized what i just told you.
Try this instead :
String s1 = resultarray.substring(0,resultarray.indexOf("*"));
String s2 = resultarray.substring(resultarray.indexOf("*")+1,resultarray.length());
double d1= Double.valueOf(s1);
double d2= Double.valueOf(s2);
Hope this helps

java Double.valueOf() returns number with one decimal place

I can't seem to get my head around this. If have tried the following approaches:
DecimalFormat df = new DecimalFormat("00000.00");
DecimalFormat df = new DecimalFormat("######.##");
But the following line always generates and IllegalArgumentException.
double price = Double.valueOf(df.format(((EditText) view
.findViewById(R.id.edit_item_price)).getText().toString()));
// Sample input passed is value of 200 or some other whole number.
item.setPrice(price);
It doesn't make sense as I only copied the obvious solutions in this forum. Most of you got the format() to work.
Originally, I didn't have these lines of code. I just call my setPrice() method after getting the item price. This works. However, Double.valueOf() has a nasty habit of using only one decimal position.
e.g. passed 200. I get 200.0 inside my item object. I figured by using DecimalFormat I could've prevented this but it appears this caused me MORE headaches instead.
When you say you pass 200 and you get 200.0, you mean you get it in a double value? If so, that doesn't matter - it's a number and 200 = 200.0 for double values.
format(...) turns a double value to a String value. You have it the other way round. That's why you get the Exception.
If the price variable is actually a double you should do
double price = Double.valueOf(((EditText) view
.findViewById(R.id.edit_item_price)).getText().toString())
But I think you want that the price is a String, then you should convert the text from the EditText to a double and that double back to a String with something like new DecimalFormat("0.00")

Android display float using settext method

iam allmoust done with my app but iam stuck on this thing , i have two int's
called "positive" and "negative" and when i procces source below it shows 0.0
total = positive + negative;
float rate = positive/total;
rate*=100;
TextView analitycs = (TextView)v.findViewById(R.id.app_scores_analitycs);
analitycs.setText(String.valueOf(rate));
What Victor said is true.
Also you might want to use something different than String.valueOf(rate) to set the text of your text view, because this method can give you an ugly representation of the number.
You should probably use String.format("%.2f", rate) ad tweak that to your needs.
Are positive and total floats/doubles?
If not, then an int/int will give you an int.
The solution would be to cast either positive or negative as a float.
try the following:
float rate = ((float)(positive))/total;

Decimal Places using double with toString, android

I am creating a simple program that performs simple math functions on the values a user enters in the EditText views. The first two EditText views contain integers and the last could be a decimal, thus the answer could also need to be in decimal form so I set the and (vis) as a double, but how can I limit the decimal places to four? Everything is running fine, the answer is just many decimal places long!
Here is my code:
public void onClick(View v) {
String a,b,t;
double vis;
EditText txtbox1 = (EditText)findViewById(R.id.A);
EditText txtbox2 = (EditText)findViewById(R.id.B);
EditText txtbox3 = (EditText)findViewById(R.id.t);
TextView tv = (TextView) findViewById(R.id.Answer);
a = txtbox1.getText().toString();
b = txtbox2.getText().toString();
t = txtbox3.getText().toString();
vis = ((Integer.parseInt(a)*1) + (Integer.parseInt(b)*2)) / (Double.parseDouble(t));
tv.setText(double.toString(vis));
}
}
Thanks so much!
You could use String.format() to make sure you only get 4 decimal places in your output. Simply replace the last line with tv.setText(String.format("%.4f", vis));.
See http://download.oracle.com/javase/tutorial/java/data/numberformat.html for more details on how to use String.format() for this purpose.
I think it's a bit too late to answer, but it may help for future purpose.
If we have a double number and we need to get the 4 decimal values we can multiply the double by 10000, and cast the double value into an integer and reverse into double again and divide the digit by 10000.
For more control, use BigDecimal.round(). You can set a MathContext with the precision and rounding rule you require (.5 is round up, vs .5 is rounded down, etc).
double vis = 21.23456;
tv.setText(new BigDecimal(vis).round(new MathContext(6, RoundingMode.HALF_UP)).toString());

Double # showing 0 on android

I'm embarrassed to ask this question, but after 45 minutes of not finding a solution I will resort to public humiliation.
I have a number that is being divided by another number and I'm storing that number in a double variable. The numbers are randomly generated, but debugging the app shows that both numbers are in fact being generated.
Lets just say the numbers are 476 & 733. I then take the numbers and divide them to get the percentage 476/733 = .64
I then print out the variable and it's always set to 0. I've tried using DecimalFormat and NumberFormat. No matter what I try though it always says the variable is 0. I know there is something simple that I'm missing, I just can't find it =/.
I imagine that you are trying to do something like this:
int x = 476;
int y = 733;
double result = x / y; // result == 0
The problem here is that you are performing integer division which gives the answer 0, and then afterwards converting the result to a double. You need to convert one or both of the numbers to floating point numbers before dividing. Here's one way to do that:
int x = 476;
int y = 733;
double result = ((double)x) / y;
I presume the 2 numbers that are being divided are "double" types?
Have you used debug mode to see the result of the division?

Categories

Resources