Monday 18 June 2018

Display number DecimalFormat after one digit of decimal without round value

1. activity_main.xml:-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    
xmlns:app="http://schemas.android.com/apk/res-auto"    
xmlns:tools="http://schemas.android.com/tools"    
android:layout_width="match_parent"   
 android:gravity="center_vertical"   
 android:orientation="vertical"   
 android:layout_height="match_parent"    
tools:context=".MainActivity">

    <TextView        
android:layout_width="match_parent"        
android:layout_height="wrap_content"        
android:text=""        
android:id="@+id/tv1"        
android:layout_gravity="center"        
android:gravity="center"/>
    <TextView        
android:layout_width="match_parent"        
android:layout_height="wrap_content"        
android:text=""        
android:id="@+id/tv2"        
android:layout_gravity="center"        
android:gravity="center"/>
    <TextView        
android:layout_width="match_parent"        
android:layout_height="wrap_content"        
android:text=""        
android:id="@+id/tv3"        
android:layout_gravity="center"        
android:gravity="center"/>

</LinearLayout>
2. MainActivity.java:-
public class MainActivity extends AppCompatActivity {
    TextView tv1,tv2,tv3;
    private String reviews;


    @Override   
 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        reviews = "2.97";
        tv1 = (TextView)findViewById(R.id.tv1);
        tv2 = (TextView)findViewById(R.id.tv2);
        tv3 = (TextView)findViewById(R.id.tv3);

        try {
            float f = Float.parseFloat(reviews);
            tv1.setText(String.format("%.1f", f) );
            tv2.setText(reviews.substring(0, reviews.indexOf('.')+2));

            // USED TO FORMAT STRING AFTRE DECIMAL TILL 1 DIGIT WITHOUT ROUNDING THE VALUE            DecimalFormat df = new DecimalFormat(".0");
            df.setRoundingMode(RoundingMode.DOWN);
            String ratingFinal = df.format(f);
            tv3.setText( ratingFinal);

        } catch (Exception e){
            e.printStackTrace();
        }


    }
}
3.Output
3.0
2.9
2.9

No comments:

Post a Comment