将数字转换为精确到2位小数的字符串

Nic*_*ick 3 java string

我目前正在使用静态String方法String.format(String, Object)格式化表示数字的字符串.

我正在截断字符串,以便小数位后只有两位数.

if (!firstString[2].replaceAll("[^\\d.]", "").equals(""))
            secondString = String.format("%.2f", Float.valueOf(firstString[2].replaceAll("[^\\d.]", "")));
Run Code Online (Sandbox Code Playgroud)

我想知道如何使格式化的字符串有两个小数位,即使它是一个整数或没有十位有效数字.

Mar*_*des 8

当然你可以使用String.format它,但为什么不使用DecimalFormat,专门为格式化数字而构建的字符串?

    double value = 32d;
    DecimalFormat decimalFormat = new DecimalFormat("#.00");
    System.out.print(decimalFormat.format(value));
Run Code Online (Sandbox Code Playgroud)