通过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:
format in class NumberFormat
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

相关文章:

  • 2021-10-29
  • 2022-01-14
  • 2022-12-23
  • 2021-08-06
  • 2022-02-10
  • 2021-09-20
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-01-26
  • 2021-10-21
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-18
相关资源
相似解决方案