Android display float using settext method - android

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;

Related

I have a few questions about MPAndroidCharts

The data in my graphs use milliseconds and look approximately like this:
[1534928499109,52],[1534928522758,49],[1534928546408,51],[1534928570036,47],[1534928593671,54],
but with many thousand data points. For some reason the points stack on top of each other like in the picture I've attached. How can I fix this? This also happens with HelloCharts.
Points stacking on top of each other.
I prefer MPAndroidChart but HelloCharts got this awesome view, previewChart. Here's an example: https://github.com/lecho/hellocharts-android. Does MPAndroidCharts support previewCharts or something similar?
I am currently using a valueformatter to change milliseconds to date. Can I somehow get the difference between the smallest and biggest currently visible value and this way dynamically change the valueformatter to format more specific time?
Thanks in advance for any answers!
Only answering 3.:
chart.visibleXRange gives you the difference between the lowest and the highest visible x value. Similarly, chart.visibleYRange gives the values for the Y axis.
Be aware that (if you have defined a dragOffsetX) when scrolled all the way to the left or the right border of the chart, then the lowest or the highest value, respectively, is the lowest/highest value actually occurring in your data, but not the x value corresponding to the left/right border of the chart. To get that value, you can use chart.getValuesByTouchPoint(...) and chart.contentRect.
I use the following function to determine the exact interval between labels which helps me decide in what granularity I want to format the labels (in my case seconds vs milliseconds). The main part which transforms the rawInterval into interval is taken from com.github.mikephil.charting.renderer.AxisRenderer.computeAxisValue and translated to Kotlin:
fun calculateIntervalBetweenLabels(): Double {
val range = chart.getValuesByTouchPoint(chart.contentRect.right, 0f, YAxis.AxisDependency.LEFT).x - chart.getValuesByTouchPoint(chart.contentRect.left, 0f, YAxis.AxisDependency.LEFT).x
val rawInterval = range / chart.xAxis.labelCount
var interval = Utils.roundToNextSignificant(rawInterval).toDouble()
val intervalMagnitude = Utils.roundToNextSignificant(10.0.pow(log10(interval).toInt())).toDouble()
val intervalSigDigit = (interval / intervalMagnitude).toInt()
if (intervalSigDigit > 5) {
interval = floor(10 * intervalMagnitude)
}
return interval
}
In simpler cases without dragOffsetX, the first line could be replaced by val range = chart.visibleXRange.
In my ValueFormatter I do this:
override fun getFormattedValue(value: Float): String {
return when {
calculateIntervalBetweenLabels().roundToLong() >= 1000 -> formatValueInSeconds(value)
else -> formatValueInMilliseconds(value)
}
}
I've figured a few things out. In case anyone comes across this in the future and wonders the same thing.
MPAndroidCharts class Entry uses Float. Max value for Float is 2^23 and everything above that is rounded, the points get the same x-value. I fix this by subtracting 1.5 billion from every value and dividing by 100. Then in the ValueFormatter, I undo this.
I don't know, yet.
My solution was to calculate the difference between every value that gets formatted in the ValueFormatter. If the difference is less than zero, the formatter has looped around and that value is the displayed interval. Another solution suggested using chart.visibleXRange, which is much simpler.

Calculator app approach

as getting into android i decided to replace the default calculator with mine. A simple calculator with the 4 operational signs. I've been giving to all buttons the right behaviour, storing every number in a 'num' ArrayList(String) and signs in a 'sign' ArrayList(String).
What i wanted to do, was to then combine numbers and signs into a string, parse it into a float and getting a result. I thought this was one of the easy/simple ways to deal with it, since when you set a float like this:
float f = 6*4-5/2+3
it gives you the right result. but it clearly does not when starting from a String, like this:
String s = "6*4-5/2+3"
Float f = Float.valueOf(s)
Is there a way to getting a result from my 2 ArrayList(String)? In the negative case, what would be a doable approach (in the sense im not an experienced programmer)I?
I Think this approach is incorrect.
I would do the following:
You would have a Textview or Edittext as the calculator "screen" on top.
then you would have all your number and operation signs buttons.
Now, every number you press, it will append to the last one on the screen, using .append()
once you tap on an operator sign - two things will happen:
1) the number in the textView will be stored as a Float (using Float.valueOf(yourTextView); in a varibale, say firstNum.
2) you will save the operator you clicked in a second variable, say String calcOper.
Now, you enter your second number, and then you would press the Equals sign.
What will happen then is simply use a Switch of If expression.
If calcOper is "-" - then do firstNum- Current number shown on screen.
If calcOper is "+" - then do firstNum+ Current number shown on screen.
At last don't forget to set the text on the TextView the result.
Good luck!

How to displaying Float/Double in meaningful form in 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.

expected<true>,but was<false>

I have a small application that converts temperature from Celsius to Fahrenheit and vice-versa. I have two RadioButtons to select the temperature i.e. Celsius or Fahrenheit and one Button and one EditText . I created a Junit to test the application.
Here is my test code:
float temparature=102;
Float expected=(float) 0;
solo.enterText(0,String.valueOf(temparature));
solo.clickOnButton("calculate");
if(solo.isRadioButtonChecked(0)){
expected=((temparature-32)*5/9);
}
else if(solo.isRadioButtonChecked(1)){
expected=((temparature*9)/5)+32;
}
String temp=expected+"";
assertEquals(true,solo.searchEditText(temp));
}
When I run the above test, test run was successful but failed saying: expected<true>but was <false>. I think there is some problem with value rounding. Please let me know what exactly is the problem.
You have String temp=expected+""; but expected is object(Float) type - Float expected.
So try expected.toString() or change Float expected to float expected.
And try to debug.
The value of expected is probably something like 102.0000001, which is not going to match the text in solo, which should be 102 (if I understand the code correctly).
You should follow the standard float comparison techniques instead of comparing Strings.
http://junit.sourceforge.net/javadoc/org/junit/Assert.html#assertEquals%28java.lang.String,%20double,%20double,%20double%29
So you'd use something like:
assertEquals("The converted temperature didn't match.", temparature, expected, 0.001);
Overall, it isn't clear what your test case is trying to validate exactly. And the title of your post doesn't indicate anything about the question.

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

Categories

Resources