我想按照以下模式将 float 格式化为字符串
X.XX
-> 当小数点前只有 1 位数字时,则为 2 位小数精度
XX.XX
-> 当小数点前有 2 位数字时,则为 2 位小数精度
XXX.X
-> 当小数点前有 3 位数字时,小数点精度为 1
XXXX..
-> 当小数点前有 4 位或更多位时,不应显示小数点
如何在 Java 中执行此操作?
最佳答案
只是使用 Decimal Format 的简单代码可能会有所帮助
float f= 24.56f;//Replace with your float number
int i = (int)f;
if(i<100)
System.out.println(new DecimalFormat("#.##").format(f));//This functions will round the last bits also i.e. greater then 4 will increase the number preceding also
else if( i < 1000)
System.out.println(new DecimalFormat("#.#").format(f));
else
System.out.println(new DecimalFormat("#").format(f));
关于java - 在android Java中格式化 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34019999/