How to Java String.format with a variable precision?

前端 未结 3 1876
名媛妹妹
名媛妹妹 2020-12-06 04:42

I\'d like to vary the precision of a double representation in a string I\'m formatting based on user input. Right now I\'m trying something like:

String foo          


        
相关标签:
3条回答
  • 2020-12-06 05:03

    You sort of answered your own question - build your format string dynamically... valid format strings follow the conventions outlined here: http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html#syntax.

    If you want a formatted decimal that occupies 8 total characters (including the decimal point) and you wanted 4 digits after the decimal point, your format string should look like "%8.4f"...

    To my knowledge there is no "native support" in Java beyond format strings being flexible.

    0 讨论(0)
  • 2020-12-06 05:09

    You can use the DecimalFormat class.

    double d1 = 3.14159;
    double d2 = 1.235;
    
    DecimalFormat df = new DecimalFormat("#.##");
    
    double roundedD1 = df.format(d); // 3.14
    double roundedD2 = df.format(d); // 1.24
    

    If you want to set the precision at run time call:

    df.setMaximumFractionDigits(precision)
    
    0 讨论(0)
  • 2020-12-06 05:11

    Why not :

    String form = "%."+precision+"f\n";
    String foo = String.format(form, my_double);
    

    or :

    public static String myFormat(String src, int precision, Object args...)
    {
        String form = "%."+precision+"f\n";
        return String.format(form, args);
    }
    
    0 讨论(0)
提交回复
热议问题