保留N位小数

通过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
原文地址:https://www.cnblogs.com/submarinex/p/1982993.html