我将在Android中使用浮点数,并保留小数点后两位。我搜索了示例,但没有找到。
有人可以帮助我吗?
float f = 2.3455f;
String test = String.format("%.02f", f);
DecimalFormat
。float f = 102.236569f;
DecimalFormat decimalFormat = new DecimalFormat("#.##");
float twoDigitsF = Float.valueOf(decimalFormat.format(f)); // output is 102.24
//double twoDigitsF = Double.valueOf(decimalFormat.format(f)); also format double value
在上面的答案中,它总是会返回2位小数。
使用String.format("%.02f", f)的示例
2.5555 -> 2.55
2.5 -> 2.50
但是你需要为2.5获得2.50吗?
为了避免获得过多的0,您可以使用这个解决方案。
val format = DecimalFormat("0.##")
return format.format(floatNum)