Reputation: 2901
I want to format a floating number into a String in following pattern
X.XX
-> when there is only 1 digit before decimal then 2 decimal precision
XX.XX
-> when there are 2 digits before decimal then 2 decimal precision
XXX.X
-> when there are 3 digits before decimal then 1 decimal precision
XXXX..
-> when there are 4 or more digits before decimal then no decimal points should be displayed
How to do this in Java?
Upvotes: 0
Views: 1819
Reputation: 2521
Assume you have float f number
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);
Upvotes: 0
Reputation: 6276
Just simple code using Decimal Format can be helpful
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));
Upvotes: 1