How to Java String.format with a variable precision?

前端 未结 3 1878
名媛妹妹
名媛妹妹 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: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);
    }
    

提交回复
热议问题