How to Round Floating point number (Double) to 2 Decimal Points in J2ME JavaME
|
|
The minimalistic design of JavaME CLDC means that a lot of packages from the standard Java has to be trimmed out and this includes the flexible NumberFormat packages which is useful for formatting numbers in Java.
The absence of NumberFormat and java.text package means that you can't even round a floating point number!
However there is a workaround to this problem, with this simple method, you can round floating point number (Double) roughly to a specific number of decimal points.
JAVA:
-
//round to 2 decimal points
-
double number = (double)(int)((bmi+0.005)*100.0)/100.0;
-
-
//round to 4 decimal points
-
double number = (double)(int)((bmi+0.00005)*10000.0)/10000.0;
The code above shows you how to round a double to 2 and 4 decimal points, you can change the number of zeros above to round it to your desired decimal points.
Hope that will help you in your JavaME / J2ME programming.






tag this
October 17th, 2007 at 8:44 pm
thnx
January 6th, 2008 at 4:15 pm
thanks lots!
June 14th, 2008 at 7:54 am
excelent!!!, very very ingenious. You are a genious!! very thanks
July 23rd, 2008 at 2:52 am
thank u very much!
September 2nd, 2008 at 1:45 am
Thanx man