通过DecimalFormat类实现
import java.util.Scanner;
import java.text.DecimalFormat;
public class Main
{
public static void main(String[] args)
{
double value;
Scanner cin = new Scanner(System.in);
value = cin.nextDouble();
// 保留两位小数
DecimalFormat df = new DecimalFormat("#.00");
String result = df.format(value);
System.out.println(result);
}
}
format
public StringBuffer format(double number, StringBuffer result, FieldPosition fieldPosition)
- Formats a double to produce a string.
- Specified by:
-
formatin classNumberFormat
- Parameters:
-
number- The double to format -
result- where the text is to be appended -
fieldPosition- On input: an alignment field, if desired. On output: the offsets of the alignment field. - Returns:
- The formatted number string
- Throws:
-
ArithmeticException- if rounding is needed with rounding mode being set to RoundingMode.UNNECESSARY - See Also:
FieldPosition