Wednesday, January 9, 2013

Convert A Decimal To An Integer In Java

The Java programming language provides access to dozens of common mathematical operations in the java.util.Math static class. By calling this class, you can round, find exponents and even perform trigonometric operations on numbers. Three methods are provided for rounding numbers, depending upon the behavior you desire: floor, ceil and round.


Instructions


1. Open the Netbeans Integrated Development Environment that came with your Java install. Alternatively, you can use any text editor or Java IDE you like, but the instructions will assume you are using Netbeans.


2. Open an existing Java file, or create a new one by clicking "File" and "New Class."


3. Add the following line to the top of the file to import the Math class:








import java.util.Math;


4. Type one of the following anywhere in your document:


int flooredValue = (int) Math.floor(3.4);


int ceilingValue = (int) Math.ceil(3.4);


int roundedValue = (int) Math.round(3.4);








The first will return the "floor" of the value. In effect, this always rounds down. The second returns the ceiling, or rounds up. "Round" will return the nearest value with 0.5 always rounded up to the next largest value. Notice, it is necessary to cast the results to integer using the "(int)" command.

Tags: java util, java util Math, util Math, will return