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:
  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: , , , , ,

Bookmark this post : These icons link to social bookmarking sites where readers can share and discover new web pages.
  • co.mments
  • del.icio.us
  • digg
  • YahooMyWeb
  • DZone
  • StumbleUpon
  • Technorati

Recommended Reading

5 smashing comments for this post.

  1. thanasis Said:

    thnx

  2. taro Said:

    thanks lots!

  3. pao Said:

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

  4. ana Said:

    thank u very much!

  5. viv Said:

    Thanx man

Leave a Comment

Subscribe by Email


Powered by FeedBlitz

 


Your Ad Here