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

0

I created 3 TextViews and 2 variables of type long .

2 of the TextViews will display the two long variables separately, the latter displaying the result of a division of the first variable ( n01 ) variable long by 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 decimal / fractional result ... if above for example, tvResult displays the value 5 as a result, when it should be 5 and a broken ...

How do I display "cracks" and limit the number of numbers after the comma?

    
asked by anonymous 01.02.2017 / 00:55

2 answers

1

Cast from n02 to 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));
    
01.02.2017 / 01:00
1

You can use the DecimalFormat , or do this below, in which 2f means you want 2 boxes after the comma. See:

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

Adapting

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