Reputation: 3520
I've been struggling with this problem for a while. I have numbers that are shown in a TextView. In this textview, I would only like the float to be shown with a precision of 3 as there is only room for 3 numbers. Here are some input - output examples of what I am trying to achieve:
1 -> 1.00
0.34 -> 0.34
-12.34 -> -12.3
123.45 -> 123
The input will always be rounded to the nearest hundredth. I've tried using String.format and even making a custom format. Currently I have logic to figure out the formatting, but there must be a one liner:
float abs_d = Math.abs(my_float);
String dist = "";
if (abs_d < 10) {
dist = String.format("%1.2f", d);
}
else if (abs_d < 100) {
dist = String.format("%2.1f", d);
}
else {
dist = String.format("%3.f",d);
}
my_text_view.setText(dist);
Perhaps there is a sneaky way to do it using the TextView? You can specify the pixel width, but how about the character width (but even then, would i accept a negative sign)? I imagine there should be some Java library to do this.
Upvotes: 0
Views: 946
Reputation: 3520
@ikegami @Jack thanks for the conversation and suggestions. This seems to get the functionality for which I'm searching:
String str = "999";
DecimalFormat f = null;
if (abs_d < 1000) {
if (abs_d < 1) {
f = new DecimalFormat("@@");
str = f.format(d);
}
else {
f = new DecimalFormat("@@@");
str = f.format(d);
}
}
my_text_view.setText(str);
Upvotes: 0
Reputation: 385600
Of course there's a one liner. Put the logic in a function called format_float
and use
my_text_view.setText(format_float(my_float));
Upvotes: 0