How Can I Display a Number Without Decimal Places in Java?
Properly formatting and displaying numbers in a Java program requires some understanding of the basic number types available for data storage. Numeric variables containing decimal points are defined and stored as "float," or floating-point number, data types. Whole number values are assigned a data type of "int," or integer. Java provides a simple conversion function that displays only the integer portion if you want to display a floating-point number without the decimal portion of the number.
Instructions
-
-
1
Identify your float variable. For example:
static float f = 9.444;
-
2
Declare an integer variable to hold the converted value and assign the new value to it:
int i = (int) f;
-
-
3
Output the data to the screen:
System.out.println("New integer value: " +i);
The output for the example code snippet is "New integer value: 9."
-
1
Tips & Warnings
Place the desired storage type in parentheses in front of the existing variable to convert and assign the value to the new variable type.
References
- Photo Credit Hemera Technologies/Photos.com/Getty Images