How to Format a Variable to One Decimal Place in Java
The Java programming language includes built-in support for non-integer numeric variables in the float and double primitive types. Floating-point values are stored in an internal representation that has a finite precision; programs can choose to display and process such values with as many decimals as they need, as long as the number of decimals is within the precision limits. In particular, you can write Java code that formats floating-point values so that they are displayed with one decimal place on whatever output the program feeds into.
Instructions
-
-
1
Include the following lines at the beginning of your Java code:
import java.util.*;
import java.text.*;
-
2
Format a "float" -- a single-precision floating point -- value to one decimal place, as in the following sample code:
DecimalFormat myFormat = new DecimalFormat("####.#");
float myFloat = 46.36778;
String formattedFloat = myFormat.format(myFloat);
System.out.println(formattedFloat);
Include as many "#" signs before the decimal point in the format as places you want to the left of the decimal point. The "float" value is formatted to one decimal place.
-
-
3
Format a "double" -- a double-precision floating point -- value to one decimal place, as in the following sample code:
DecimalFormat myFormat = new DecimalFormat("####.#");
double myDouble = 2.718281828;
String formattedDouble = myFormat.format(myDouble);
System.out.println(formattedDouble);
Include as many "#" signs before the decimal point in the format as places you want to the left of the decimal point. The "double" value is formatted to one decimal place.
-
1
References
- Photo Credit Justin Sullivan/Getty Images News/Getty Images