how to add 1 decimal place to score system - android

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

Related

using if statement with bigger than and less than

so what i have is 2 editText one for minimum number and one for maximum number and when the user clicks the button the app generate a random number between the 2 given number (I got it) but if the user entered the maximum number in the minimum number field the app crashes what i want to accomplish is if the user enters the maximum number in the minimum number field set the maximum number field to minimum number + 1 and try again automatically I tried the code below and its working if the user entered the values in the right please but if the user entered the maximum number in the minimum number field the app crash
Button gen = (Button)findViewById(R.id.button);
final EditText mini = (EditText)findViewById(R.id.mini);
final EditText maxi = (EditText)findViewById(R.id.maxi);
final TextView res = (TextView)findViewById(R.id.result);
final Random r = new Random();
final int[] number = {0};
gen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int minn = Integer.parseInt(mini.getText().toString());
int maxx = Integer.parseInt(maxi.getText().toString());
if (minn>=maxx){
maxi.setText(minn+1);
maxx = Integer.parseInt(maxi.getText().toString());
number[0] = minn + r.nextInt(maxx - minn + 1);
res.setText(String.valueOf(number[0]));
}else{
number[0] = minn + r.nextInt(maxx - minn + 1);
res.setText(String.valueOf(number[0]));
}
}
});
}
Replace the following...
maxi.setText(minn+1);
With...
maxi.setText(String.valueOf(minn+1));
Passing int value instead of String value into the setText method causing the crash problem.
I think you should do something like this:
if (minn>=maxx){
maxi.setText(String.valueOf(minn));
mini.setText(String.valueOf(maxx));
maxx = Integer.parseInt(maxi.getText().toString());
minn = Integer.parseInt(minn.getText().toString());
number[0] = minn + r.nextInt(maxx - minn + 1);
res.setText(String.valueOf(number[0]));
}
number[0] = minn + r.nextInt(maxx - minn + 1);
res.setText(String.valueOf(number[0]));

Output string with decimal format limited to 2 dp

Stuck on this which im sure there is an easy solution to, just cannot work it out!!
I have tried decmialformat, numberformat, string.format() etc and nothing works. .
code below, i want to calculation to just show the output limited to 2 decimal places. Have spent the last 2 hours trying various methods all of which causes the app to crash when run...
Output = (Output1 / (1 -(Output2/100)))
String OutputString = String.valueOf(Output);
Num.setText(OutputString);
Try this :
String OutputString = String.format("%.2f", Output);
Num.setText(OutputString);
String.format() to make sure you only get 2 decimal places in your output.
please try this:
double Output = (Output1 / (1 -(Output2/100d)))
Num.setText(String.format("%.2f",Output));
Hope this solves your problem.
Best regards
If you want to Limit the number of Digits before and after the 'decimal_point' then you can use my solution.
private class DecimalNumberFormatTextWatcher implements TextWatcher{
int pos;
int digitsBeforeDecimal = 6;
int digitsAfterDecimal = 2;
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
if(s.length() > 2)
pos = start;
else {
pos = start + 2;
}
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
mEdittext.removeTextChangedListener(this);
String text = s.toString();
if(text!= null && !text.equals("")){
if(!text.contains("$")){ //if it does not contains $
text = "$"+text;
} else {
if (text.indexOf("$") > 0) { //user entered value before $
text = s.delete(0, text.indexOf("$")).toString();
}else {
if(!text.contains(".")){ // not a fractional value
if(text.length() > digitsBeforeDecimal+1) { //cannot be more than 6 digits
text = s.delete(pos, pos+1).toString();
}
} else { //a fractional value
if(text.indexOf(".") - text.indexOf("$") > digitsBeforeDecimal+1){ //non fractional part cannot be more than 6
text = s.delete(pos,pos+1).toString();
}
if((text.length() - text.indexOf(".")) > digitsAfterDecimal+1) { //fractinal part cannot be more than 2 digits
text = s.delete(text.indexOf(".") + 2, text.length() - 1).toString();
}
}
}
}
}
mEdittext.setText(text);
mEdittext.setSelection(pos);
mEdittext.addTextChangedListener(this);
}
}
mEdittext.addTextChangedListener(new DecimalNumberFormatTextWatcher());
This also adds a currency sign as soon as the user types the value.
HOPE THIS HELPS ANYONE.

Change the step size of a NumberPicker

Is it possible to do that in a more convenient way than handling it in the OnScrollListener event? Pity it doesn't have a step size attribute...
The NumberPicker in Android has a method called setDisplayedValues.
You can use this one to show custom values (it takes an array of Strings) and then map them when you need the value.
So if you need steps of 5 in an minute picker, for example, you can create an array like this:
String[] minuteValues = new String[12];
for (int i = 0; i < minuteValues.length; i++) {
String number = Integer.toString(i*5);
minuteValues[i] = number.length() < 2 ? "0" + number : number;
}
minutePicker.setDisplayedValues(minuteValues);
And then when you get the value in the OnValueChangeListener, you just need to cast it back to an integer:
Integer.parseInt(minuteValues[newVal]);
To set a step count of '5' for example, use the NumberPicker.Formatter:
NumberPicker.Formatter formatter = new NumberPicker.Formatter() {
#Override
public String format(int value) {
int temp = value * 5;
return "" + temp;
}
};
numberPicker.setFormatter(formatter);
Why not just add an OnValueChangeListener Something like:
numberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
picker.setValue((newVal < oldVal)?oldVal-5:oldVal+5);
}
});
The NumberPicker in Android has a method called setDisplayedValues. You can use this one to show custom values (it takes an array of Strings) and then map them when you need the value.
For example, you can create a function like this:
public String[] getArrayWithSteps (int iMinValue, int iMaxValue, int iStep)
{
int iStepsArray = (iMaxValue-iMinValue) / iStep+1; //get the lenght array that will return
String[] arrayValues= new String[iStepsArray]; //Create array with length of iStepsArray
for(int i = 0; i < iStepsArray; i++)
{
arrayValues[i] = String.valueOf(iMinValue + (i * iStep));
}
return arrayValues;
}
So, you should call the method> NumberPicker.setDisplayedValues, for example:
int min = 5;
int max = 180;
int step = 10;
String[] myValues = getArrayWithSteps(min, max, step); //get the values with steps... Normally
//Setting the NumberPick (myNumberPick)
myNumberPick.setMinValue(0);
myNumberPick.setMaxValue((max-step) / min + 1); //Like iStepsArray in the function
//Because the Min and Max Value should be the range that will show.
//For example, Min = 0 and Max = 2, so the NumberPick will display the first three strings in the array String (myValues);
myNumberPick.setDisplayedValues(myValues);//put on NumberPicker
For get the Value in the NumberPick:
String sValue = String.valueOf(10+(myNumberPick.getValue()*5)); //->> (iMinValue + (myNumberPick.getValue()*iStep))
When using methods described above, one needs to be aware that the picker allows user not only to select a value by scrolling, but also by entering it with keyboard.
By default, the input type of the input field is set to TYPE_CLASS_NUMBER, and therefore user is presented with numerical keyboard. It seems that when you use setDisplayedValues the picker changes the type to TYPE_CLASS_TEXT, however, when you use setFormatter the input type is not changed.
Therefore using formatter in this case may lead to unexpected behavior. Let's say you want the user to be able to pick only the values "0" or "5". You may have code like this:
NumberPicker numberPicker = (NumberPicker) findViewById(R.id.my_number_picker);
numberPicker.setMinValue(0);
numberPicker.setMaxValue(1);
numberPicker.setFormatter(v -> v == 0 ? "0" : "5");
However, in this scenario the user is presented with the numerical keyboard, but is able only to enter only "0" or "1".
If you use instead:
numberPicker.setDisplayedValues(new String[] { "0", "5" });
the user will see the text keyboard, but will be able to enter "0" or "5" as expected.
If you are bothered with the text keyboard you can use reflection to access the private field and set the input type back to number (which is of course not recommended unless really necessary). The field is called "mInputText", or "mText" if you target oldies goldies like Gingerbread.
try {
Field inputField = NumberPicker.class.getDeclaredField("mInputText");
inputField.setAccessible(true);
EditText inputText = (EditText) inputField.get(numberPicker);
inputText.setRawInputType(InputType.TYPE_CLASS_NUMBER);
} catch (ClassCastException e) {
// Just ignore this exception and do nothing.
} catch (IllegalAccessException e) {
// Just ignore this exception and do nothing.
} catch (NoSuchFieldException e) {
// Just ignore this exception and do nothing.
}
This is better approach for ajpolt solution
with any predefined step size, it support for custom value set via keyboard.
final NumberPicker np = (NumberPicker) dialogView.findViewById(R.id.numberPicker1);
np.setMaxValue(1000); // max value 1000
np.setMinValue(0); // min value 0
np.setValue(defValue);
np.setWrapSelectorWheel(false);
final int m_oldFocus = np.getDescendantFocusability();
np.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
np.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
np.setDescendantFocusability(m_oldFocus);
return false;
}
});
np.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker numberPicker, int oldVal, int newVal) {
int stepSize = 10;
if(newVal%stepSize !=0){
if(newVal < oldVal){
numberPicker.setValue(((int)(newVal/stepSize)) *stepSize);
}else{
numberPicker.setValue((((int)(newVal/stepSize)) *stepSize ) +stepSize );
}
}else{
numberPicker.setValue(newVal);
}
}
});
*I know this is 5 years old Question, but might be useful for somebody

Change textViews when they equal each other?

I have two textViews in my app right now. One textView serves as a Counter and the other servers as the Limit. What I want to accomplish is when the Counter equals the Limit, the Counter is set back to ZERO and the Limit is increased by 100.
private int i = 0;
Spinner spinnerMonsters = (Spinner) findViewById(R.id.spinnerMonsters);
TextView textViewBattleResults = (TextView) findViewById(R.id.textViewBattleResults);
TextView textViewXPValue = (TextView) findViewById(R.id.textViewXPValue);
TextView textViewXpNextLevel = (TextView) findViewById(R.id.textViewXpNextLevel);
if (textViewXPValue.getText().toString().equals(textViewXpNextLevel.getText().toString())) {
int newLimit = Integer.parseInt(textViewXpNextLevel.getText().toString()) + 100;
textViewXpNextLevel.setText(newLimit + "");
textViewXPValue.setText("0");
}
else {
textViewXPValue.setText(textViewXPValue.getText().toString());
textViewXpNextLevel.getText().toString();
}
//Monster sequences
if (spinnerMonsters.getSelectedItem().toString().equals("(0) Training Dummy")) {
textViewBattleResults.setText("You have killed Training Dummy for 10 experience points!");
i = i+10;
textViewXPValue.setText(String.valueOf(i));
}
else {
textViewBattleResults.setText(" ");
textViewXPValue.setText(textViewXPValue.getText().toString());
}
if (spinnerMonsters.getSelectedItem().toString().equals("(2) Cockroach")) {
textViewBattleResults.setText("You have killed a Cockroach for 27 experience points!");
i = i+27;
textViewXPValue.setText(String.valueOf(i));
}
else {
textViewBattleResults.setText(" ");
textViewXPValue.setText(textViewXPValue.getText().toString());
}
}
});
The problem here is that the counter will count up by ten when the button is clicked. But when the Counter equals the Limit, the Limit increases by 100 and the Counter remains at the same number and doesn't reset back to ZERO.
Any suggestions..?
EDIT
Also, how would i do the same thing but if the Counter was Equal to or Greater than the Limit?
You don't reset value of i to zero. You first set text of xpvalue to zero, but then you set it's text to current value ofi, which is not zero.

android pass a number through onclicklistener

I am trying to ask a user for 2 numbers x and y. When the user clicks the button it will subtract y from x and give the total. What I would like it to do is save the total, and the next time you click the button, it will subtract y from the total. I know I am not passing the total back through again, but I am not sure where to begin.
subtract.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) throws NumberFormatException {
if (v == subtract)
{
NumberFormat currencyFormatter;
currencyFormatter = NumberFormat.getCurrencyInstance(currentLocale);
String bString;
String x = startingmoney.getText().toString();
String y = submoney.getText().toString ();
double total = 0.00;
double xm = 0.00;
double ym =0.00;
try
{
xm = Double.parseDouble(x);
}
catch(NumberFormatException n)
{
xm = 0.00;
}
try
{
ym = Double.parseDouble(y);
}
catch(NumberFormatException n)
{
ym = 0.00;
}
total = xm -ym;
bString = currencyFormatter.format(total);
endmoney.setText(bString);
tracker.setText("you have entered " + bString +"\n" + tracker.getText().toString());
There are many ways to do this. One possible way is to make the variable "x" and "y" static. This may not meet your requirement, since you may change the value of "x" and "y" dynamically.
Another way is to change the implement of OnClickListener. You can use it as,
class MyOnClickListener implements OnClickListener
and pass the class (the class which calls "setOnClickListener") to MyOnClickListener, that is, the constructor of MyOnClickListener is like,
MyOnClickListener(CLASS clazz){
this.clazz = clazz;
}
And you can do subtraction with clazz.getX() and clazz.getY().

Categories

Resources