In this video it shows how to limit the number of decimal points of a float or decimal while printing it on a textView widget of Android App. It basically uses below line of code to limit the decimal places.
String stringFormatted = String.format("%.03f", floatData);
I hope you like this video. For any questions, suggestions or appreciation please contact us at: https://programmerworld.co/contact/ or email at: programmerworld1990@gmail.com
Complete source code and other details:
package com.programmerworld.fixeddecimalpointsinfloat;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
public class MainActivity extends AppCompatActivity {
private Float aFloatNumber = .621478f;
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_main);
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
textView = findViewById(R.id.textView);
textView.setText(String.valueOf(aFloatNumber));
return insets;
});
}
public void buttonFixDecimalPoints(View view){
textView.setText(String.format("%.03f", aFloatNumber));
}
}
No changes in any other code or files is required.
Screenshots:
Excerpt:
The provided content demonstrates how to restrict the number of decimal places when displaying a float or decimal on an Android App’s textView widget. It involves using the following line of code to achieve this formatting:
String stringFormatted = String.format(“%.03f”, floatData);
The MainActivity class features the necessary code for this implementation, including setting up the textView and utilizing the
String.format
method. ThebuttonFixDecimalPoints
function also enables the user to trigger the update of the textView with the formatted float number.
The post also includes images showcasing the expected visual output on the Android app. For further inquiries or feedback, individuals are directed to contact the provided email address or website.
Complete source code and additional details are provided, along with a link to a YouTube video explaining the process.