Home Java Beginners Rounding off in Java - Round two decimal places
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Rounding off in Java - Round two decimal places

Advertisement
In this section, you will learn about how to round the figure up to two decimal places in java.

Rounding off in Java - Round two decimal places

     

In this section, you will learn about how to round the figure up to two decimal places in java. 

Round: This is the process of rounding with dollar amounts and provides the result in more than two decimal places after division. There are following methods to used in rounding the data:

Methods  Data  Rounded Data

Round Half Up   45.558  45.56
Round Half Down  45.555  45.55
Round Up  45.558  45.56
Round Down  45.558   45.55

Description of program:

The following program round two decimal places of the given number. It means numbers are rounded into the above methods and shows the number in two figures after decimal point. Here, apply the Round() method for rounding the given number and print the following output. 

Here is the code of program:

public class RoundTwoDecimalPlaces{
  public static void main(String[] args) {
  float num = 2.954165f;
  float round = Round(num,2);
  System.out.println("Rounded data: " + round);
  }

  public static float Round(float Rval, int Rpl) {
  float p = (float)Math.pow(10,Rpl);
  Rval = Rval * p;
  float tmp = Math.round(Rval);
  return (float)tmp/p;
  }
}

Download this example.

Output of program:

C:\vinod\Math_package>javac RoundTwoDecimalPlaces.java

C:\vinod\Math_package>java RoundTwoDecimalPlaces
Rounded data: 2.95
Advertisements

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: March 18, 2008

Ask Questions?    Discuss: Rounding off in Java - Round two decimal places   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
chandan
June 9, 2011
Testing on the Java

This example is not working
Pavan
June 27, 2011
Round Down

Sir, Can u please let me know how we can able to use Round Down function for following example 65290 should be like 65200???
sudhansu sekhar nayak(odisha)
November 13, 2011
without using math function

Sir my question is "without using any function".plz help me...
sudhansu sekhar nayak
November 13, 2011
without using math function

sir my question is "without using math function".
Sivakumar
July 26, 2012
Another Method

for this you can use "new DecimalFormat("#.##").format(aFloatVal);"
DMCA.com