使用 %1$f 但没有尾随零
Using %1$f but without trailing zeros
我试图寻找解决这个问题的办法,但我不确定如何提出这个问题。
我要用文字和数字填充 TextView,我将其设置在 Activity 中。
float leftTimeSecs = leftTime / 1000;
float roundedLeftSecs = round(leftTimeSecs, 3);
//How to access this directly from "strings" or .xml files
duration.setText(getString(R.string.time_data_sec, roundedLeftSecs,
getString(R.string.seconds)));
我设置文本的字符串是:
<string name="time_data_sec">Duration: %1$f %2$s</string>
调用的轮函数是
public static float round(float value, int places) {
if (places < 0) throw new IllegalArgumentException();
BigDecimal bigDecimal = new BigDecimal(value);
bigDecimal = bigDecimal.setScale(places, RoundingMode.HALF_UP);
return bigDecimal.floatValue();
}
我希望输出打印 roundedLeftSecs 的值(leftTime 四舍五入到三个位置)但是当我不对 roundedLeftSecs 进行硬编码时,它会在四舍五入后产生许多尾随零。
我发现 %1$d 是一个小数占位符,但它不允许我将其与浮点数或双精度表达式一起使用,所以我不确定如何去掉这个零,或者是否有可能.
对于那些曾经遇到过同样问题的人,我通过使用 %1$s 并将我的舍入数字转换为字符串来解决它,它完美地工作了!
这里是我想四舍五入的地方:
float leftTimeSecs = leftTime / 1000;
float roundedLeftSecs = round(leftTimeSecs, 3);
String roundedLeftSecString = Float.toString(roundedLeftSecs);
duration.setText(getString(R.string.time_data_sec, roundedLeftSecString,
getString(R.string.seconds)));
这是字符串:
<string name="time_data_sec">Duration: %1$s %2$s</string>
我试图寻找解决这个问题的办法,但我不确定如何提出这个问题。
我要用文字和数字填充 TextView,我将其设置在 Activity 中。
float leftTimeSecs = leftTime / 1000;
float roundedLeftSecs = round(leftTimeSecs, 3);
//How to access this directly from "strings" or .xml files
duration.setText(getString(R.string.time_data_sec, roundedLeftSecs,
getString(R.string.seconds)));
我设置文本的字符串是:
<string name="time_data_sec">Duration: %1$f %2$s</string>
调用的轮函数是
public static float round(float value, int places) {
if (places < 0) throw new IllegalArgumentException();
BigDecimal bigDecimal = new BigDecimal(value);
bigDecimal = bigDecimal.setScale(places, RoundingMode.HALF_UP);
return bigDecimal.floatValue();
}
我希望输出打印 roundedLeftSecs 的值(leftTime 四舍五入到三个位置)但是当我不对 roundedLeftSecs 进行硬编码时,它会在四舍五入后产生许多尾随零。
我发现 %1$d 是一个小数占位符,但它不允许我将其与浮点数或双精度表达式一起使用,所以我不确定如何去掉这个零,或者是否有可能.
对于那些曾经遇到过同样问题的人,我通过使用 %1$s 并将我的舍入数字转换为字符串来解决它,它完美地工作了!
这里是我想四舍五入的地方:
float leftTimeSecs = leftTime / 1000;
float roundedLeftSecs = round(leftTimeSecs, 3);
String roundedLeftSecString = Float.toString(roundedLeftSecs);
duration.setText(getString(R.string.time_data_sec, roundedLeftSecString,
getString(R.string.seconds)));
这是字符串:
<string name="time_data_sec">Duration: %1$s %2$s</string>