Textview is not displaying decimal numbers of a long type variable!

Asked

Viewed 877 times

0

I created 3 Textviews and 2 variables of the type long.

2 of the Textviews will display the two long variables separately, while the last one displays the result of a split of the first (N01) long variable for the second (N02). => N01/N02

Mainactivity:

package genesysgeneration.along;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private TextView tvN01, tvN02, tvResult;
    private long n01, n02;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvN01=(TextView)findViewById(R.id.tvN01);
        tvN02=(TextView)findViewById(R.id.tvN02);
        tvResult=(TextView)findViewById(R.id.tvResult);

        n01=17;
        n02=3;

        tvN01.setText(String.valueOf(n01));
        tvN02.setText(String.valueOf(n02));
        tvResult.setText(String.valueOf(n01/n02));


    }
}

The problem is when tvResult (the Textview that was used to display the division of N01/N02) must display a result decimal/fractional... In the above case for example, tvResult displays the value 5 as a result, when it should be 5 and a broken one...

How do I display the "crackers" and how to limit the number after the comma?

  • http://answall.com/questions/174459/formatar-resultado-de-uma-divis%C3%A3o-de-inteiros/174460

  • the guy long represents integers. long never has decimals. Therefore the answers of colleagues require the conversion of type.

  • Vlw man, in fact it was much easier changing to double, I didn’t want to, but it simplified a lot

2 answers

1


Cast a cast of n02 for float:

tvResult.setText(String.valueOf(n01 / (float) n02));

With a limited number of decimal places:

// altere 2 em "%.2f" para a quantidade de casas decimais
tvResult.setText(String.format("%.2f", n01 / (float) n02));
  • VLW!!! but I limit the number after the comma in which way?

  • change 2 to "%. 2f" for the number of decimals after the comma

1

You can use the Decimalformat, or do so below, in which 2f means you want 2 houses after the comma. See:

String.format("%.2f", number);

Adapting

long valor = n01 /n02;
tvResult.setText(String.valueOf(String.format("%.2f", valor)));

Browser other questions tagged

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