How to Round Floating point number (Double) to 2 Decimal Points in J2ME JavaME
August 24th, 2007 Posted in J2ME / JavaME, Tips, Tricks, Guide, newbie
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.
[tags]j2me,javame,midp,java,sdk,j2se[/tags]
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
October 11th, 2008 at 8:32 am
Thanks
March 19th, 2009 at 1:46 pm
Awesome! Its a very small snippet but very useful. You saved my hell lot of time. Thanks man. You rocks.
May 19th, 2009 at 1:06 am
This is not rounding, is trunking.
22.92893723062 turns into 22.9288 and not 22.9289
47.026586582836 turns 47.0265 and not 47.0266