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

Asked

Viewed 443 times

1

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

Can anyone help me on that? 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));
        }
    }
    }
}
  • 1

    Only use some formatter which, when it is only zero after comma, remove decimal place, do not need to change type

  • And how do I do that? I’m new to programming, and in the research I do, there’s never what I want!

  • 3

    If you don’t see what you want in the searches you do, it’s because you’re not doing the right searches! : D. It seems that it is not yet necessary to have some knowledge to know what to look for. As a small aside, start by indenting the code which has much more impact and positive effects than you might think. Regarding the problem itself, you can see if the result of the division is equal to the same result converted to (int), This allows you to know whether you should have decimals or not.

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 on IDEONE.


Basically we’re trading any amount of zeros (0+) at the end of the line ($) by "empty" (""), and then trading any point at the end of the line also for empty.


Using operations of String

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

Upshot:

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 on IDEONE.


Basically we are dividing the string in a array by decimal point.

  • How we’re using a double, there will always be a decimal point to divide;

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

  • if you have two, concatenate with a comma.

Note that it is a base only, then you optimize.

  • NOTE: with float also works normally. See: https://ideone.com/clo5Dg

  • Could you show me how my code would look? Like I said, I’m really bad at programming, and I have no idea where and how to adapt it to my code! ;(

  • Hey @Bacco, valeus amigao, it means that this is how I treat the "." to pass as parameter of ". split()", gee man, I didn’t know, kkkkkk, I picked up here and had to do the famous "Ambi", and Peor, kkkk, I went to "Ambi" in response, rererere

  • now I ask you, why you have to have two " "you would know to say?

  • @Armandomarquesnephew split accepts a regular expression, not a common string; point alone means "any character". The first backslash is to escape the next bar (for Java), the second is to escape the point. That is, in java it turns into a string. In regex, \. turns the "dot" character literally. The $ in Regex means "end of the line, and the sequence 0+$ means "one or more zeros at the end of the line". Train here: http://regexpal.com

  • @Denniswadson just copy the "autoclaves" function the way it is and use it in your code.

  • 1

    Pow, good to know, maybe because I found a small detail not I tried to go after, even because Gambi worked, but so clean the code well, valeus mano veio!

  • So it’s just me putting in any part of the code?

  • @Bacco, I pasted your code there, but I don’t know how to use it? Can you explain to me where I put it?

  • setCurrentString(autoclaves(result));

Show 5 more comments

3

A simple way to see if the result has decimal part or not is to compare it with the conversion of the value into integer. That is to say if 2.5 has no decimal part would do 2.5 == (int)2.5 that would give him false.

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

Combining these two ideas can have the following function to obtain 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);
    }
}

Which then calls 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
  • Could you show me how my code would look? Like I said, I’m really bad at programming, and I have no idea where and how to adapt it to my code! ;(

0

I usually do that 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(".") once, so I used realce(".","_") to avoid.

this code snippet does the following:
Convert your variable float to a string with String.valueOf(...);.
Split her into two using ...replace(...,...).split(...);.
Then take the first part of the created vector and convert it to integer again with Integer.parseInt(...);.

I hope that’s what you want.

  • Could you show me how my code would look? Like I said, I’m really bad at programming, and I have no idea where and how to adapt it to my code! ;(

Browser other questions tagged

You are not signed in. Login or sign up in order to post.