[英]Formatting Floating point numbers in android Java
我想按照以下模式将浮点数格式化为字符串
X.XX
>当小数点前只有1位数字,然后小数点后2位精度
XX.XX
>当小数点前有2位数字,则小数点后2位
XXX.X
>如果十进制前有3位数字,则精度为1位小数
XXXX..
>如果小数点前有4个或更多数字,则不应显示小数点
如何用Java做到这一点?
使用十进制格式的简单代码可能会有所帮助
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));
假设你有漂浮F数
float f;
int a = (int) f;
String res = null;
if (a<100) res = String.format("%.2f");
else if (a<1000) res = String.format("%.1f");
else res = String.valueOf(a);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.