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:
  1. //round to 2 decimal points
  2. double number = (double)(int)((bmi+0.005)*100.0)/100.0;
  3.  
  4. //round to 4 decimal points
  5. 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]

 

Random Posts

8 Responses to “How to Round Floating point number (Double) to 2 Decimal Points in J2ME JavaME”

  1. thanasis Says:

    thnx



  2. taro Says:

    thanks lots!



  3. pao Says:

    excelent!!!, very very ingenious. You are a genious!! very thanks



  4. ana Says:

    thank u very much!



  5. viv Says:

    Thanx man



  6. Eric Says:

    Thanks



  7. Sameer Nafdey Says:

    Awesome! Its a very small snippet but very useful. You saved my hell lot of time. Thanks man. You rocks.



  8. Léo Says:

    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



Leave a Reply