我使用以下代码,使用字符串连接在一个字符串中输出6个双精度值。对我来说很有效,但我猜是糟糕的实践(setText中的字符串连接)。
allUpM_TextView.setText(
"Mass [kg]: %.0f".format(AllUpM) + " Mass/V [kg/m2]: %.3f".format(MperV) +
"\nMax Alt [m]: %.1f".format(Alt) +
"\nTemp [deg C]: %.1f".format(Temp_a) +
"\nPres [mBar]: %.1f".format(Pres_a) +
"\nLift [kg]: %.1f".format(Lift) )所以我想用一个资源字符串来实现:
<string name="outputTxt">Mass [kg]: %1$s Mass/V [kg/m2]: %2$s
\nMax Alt [m]: %3$s
\nTemp [deg C]: %4$s nPres [mBar]: %5$s
\nLift [kg]: %6$s</string>和
val string = getString(R.string.outputTxt,
AllUpM.toString(),
MperV.toString(),
Alt.toString(),
Temp_a.toString(),
Pres_a.toString(),
Lift.toString()
)
allUpM_TextView.setText(string)双精度输出为全精度。
如何实现"%.1f“或"%.3f”之类的Double格式?
任何人在他们的第一个Android应用程序的帮助后,最后一次编程Fortan在30年前。
发布于 2021-05-03 01:24:05
fun Double.toFormattedString(n : Int) : String {
return "%.${n}f".format(this).toString() // not tested, maybe toString isn't required
}这将帮助您获得n位小数(称为扩展函数,如果您以前没有见过该语法的话)
然后在每个double上使用它,而不是调用toString:
val string = getString(R.string.outputTxt,
AllUpM.toFormattedString(2),
MperV.toFormattedString(2),
Alt.toFormattedString(2),
Temp_a.toFormattedString(2),
Pres_a.toFormattedString(2),
Lift.toFormattedString(2)
)
allUpM_TextView.setText(string)https://stackoverflow.com/questions/67359146
复制相似问题