Get value Integer in end .00 and float value in .01 to 0.9

1

I have this code below that is from a calculator, however I have a problem: I wanted to return a float value when dividing 5/2 = 2.5 and returning an integer value when dividing 4/2 = 2 and not 2.0 !

Can anyone help me with this? The code is this:

public class CalcActivity extends Activity
{
    TextView tvScreenCalc;
    String currentString="0",previusString=null;
    boolean isTempStringShown=false;
    int currentopperand=0;
    @Override public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_calc);
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT);
        tvScreenCalc=(TextView)findViewById(R.id.tvScreenCalc);
        int numberButtons[]={R.id.button0,R.id.button1,R.id.button2,R.id.button3,R.id.button4,R.id.button5,R.id.button6,R.id.button7,R.id.button8,R.id.button9};
        NumberButtonClickListener numberClickListener=new NumberButtonClickListener();
        for(int id:numberButtons)
        { View v=findViewById(id);
            v.setOnClickListener(numberClickListener);
        }
        int opperandButtons[]={R.id.buttonPlus,R.id.buttonMinus,R.id.buttonDivide,R.id.buttonTimes,R.id.buttonDecimal,R.id.buttonClear,R.id.buttonEquals};
        OpperandButtonClickListener oppClickListener=new OpperandButtonClickListener();
        for(int id:opperandButtons)
        { View v=findViewById(id);
            v.setOnClickListener(oppClickListener);
        }
        setCurrentString("0");
    }
    void setCurrentString(String s)
    { currentString=s;
        tvScreenCalc.setText(s);
    }
    class NumberButtonClickListener implements OnClickListener
    { @Override public void onClick(View v)
    { if(isTempStringShown)
    { previusString=currentString;
        currentString="0";
        isTempStringShown=false;
    }
        String text=(String)((Button)v).getText();
        if(currentString.equals("0"))setCurrentString(text);
        else setCurrentString(currentString+text);
    }
    }
    class OpperandButtonClickListener implements OnClickListener
    { @Override public void onClick(View v)
    { int id=v.getId();
        if(id==R.id.buttonClear)
        { isTempStringShown=false;
            setCurrentString("0");
            previusString=null;
        }
        if(id==R.id.buttonDecimal)if(!currentString.contains("."))setCurrentString(currentString+".");
        if(id==R.id.buttonPlus||id==R.id.buttonMinus||id==R.id.buttonTimes||id==R.id.buttonDivide)
        { currentopperand=id;
            previusString=currentString;
            isTempStringShown=true;
        }
        if(id==R.id.buttonEquals)
        { double curr=Double.parseDouble(currentString);
            double result=0;
            if(previusString!=null)
            { double prev=Double.parseDouble(previusString);
                switch(currentopperand)
                { case R.id.buttonPlus: result=prev+curr; break;
                    case R.id.buttonMinus: result=prev-curr; break;
                    case R.id.buttonTimes: result=prev*curr; break;
                    case R.id.buttonDivide: result=prev/curr; break;
                }
            }
            setCurrentString(Double.toString(result));
        }
    }
    }
}
    
asked by anonymous 20.06.2018 / 03:38

3 answers

5

There are many ways, here are some:

Using RegEx

static String autocasas(double numero)
{
   return String.valueOf(numero).replaceAll("(\.?0+|\.)$","");
}

See working at IDEONE .


Basically we are exchanging any amount of zeros ( 0+ ) at the end of the line ( $ ) by "empty" ( "" ), and then changing any point at the end of the line also by empty .


Using String operations

static String autocasas(double numero)
{
   String[] partes = String.valueOf(numero).split("\.");
   if (partes[1].equals("0")) return String.valueOf(partes[0]);
   return String.valueOf(partes[0]) + "," + String.valueOf(partes[1]);
}

Result:

System.out.println(autocasas(5.0/7.0)); // 0,7142857142857143
System.out.println(autocasas(5.0/2.0)); // 2,5
System.out.println(autocasas(123));     // 123

See working at IDEONE .


We are basically dividing the string into an array by the decimal point.

  • As we are using double , there will always be a decimal point to divide;

  • If the second part is a "loose" zero, it returns only the first;

  • If you have two, concatenate it with a comma.

Note that it's a baseline only, then you optimize it.

    
20.06.2018 / 13:05
3

A simple way to tell if the result has a decimal part or is not comparing with the integer value conversion. That is to say if 2.5 has no decimal part would be 2.5 == (int)2.5 that would give you false.

To get a float with two boxes after the comma, you can use String.format using %.2f as format specifier.

Combining these two ideas can have the following function to get the result as String :

public static String obterResultadoFormatado(float res){
    if (res == (int)res){
        return String.valueOf((int)res);
    }
    else {
        return String.format("%.2f", res);
    }
}

Then call directly with the result of the calculation:

float num1 = 5;
float num2 = 4;

Log.d("CalcActivity", obterResultadoFormatado(num1 / 2)); // 2,50
Log.d("CalcActivity", obterResultadoFormatado(num2 / 2)); // 2
    
20.06.2018 / 12:10
0

I usually do so in these cases:

// ...
float vf = 5/2;
String [] vs = String.valueOf(vf).replace(".","_").split("_");
int vi = Integer.parseInt(vs[0]);
// ...

In the above case, I had problems with split(".") one time, so I used realce(".","_") to avoid.

This snippet of code does the following:
Converts your float variable to a string with String.valueOf(...); .
Separate it in two using ...replace(...,...).split(...); . Then it takes the first part of the created vector and converts it to integer again with Integer.parseInt(...); .

I hope this is what you're after.

    
20.06.2018 / 08:39