zoukankan      html  css  js  c++  java
  • 保留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
  • 相关阅读:
    Linux
    Linux
    Linux
    Linux
    Linux
    shell tr命令
    grep 正则表达
    shell 运算符
    shell 重定向
    bzoj 1026 DP,数位统计
  • 原文地址:https://www.cnblogs.com/submarinex/p/1982993.html
Copyright © 2011-2022 走看看