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

时间:2014-07-17 13:12:17

标签: java string

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

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

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

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

3 个答案:

答案 0 :(得分:8)

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

    double value = 32d;
    DecimalFormat decimalFormat = new DecimalFormat("#.00");
    System.out.print(decimalFormat.format(value));

答案 1 :(得分:0)

这是一个例子:

String firstString ="3.22222222225456465";
String newString= String.format("%.2f", Float.valueOf(firstString));
System.out.println(newString);

String intString =3;
String newString= String.format("%.2f", Float.valueOf(intString ));
System.out.println(newString);

答案 2 :(得分:0)

我知道,这不是很重要......但仅仅是关于表现的2美分:

static String formatUsingDecimalFormat(double value) {
    DecimalFormat decimalFormat = new DecimalFormat("#.00");
    return decimalFormat.format(value);
}

// http://stackoverflow.com/questions/8553672/a-faster-alternative-to-decimalformat-format
static String formatBy_Peter_Lawrey(double d) {
    StringBuilder builder = new StringBuilder();

    if (d < 0) {
        builder.append('-');
        d = -d;
    }
    long scaled = (long) (d * 1e6 + 0.5);
    long factor = 100;
    int scale = 3;
    while (factor * 10 <= scaled) {
        factor *= 10;
        scale++;
    }
    while (scale > 0) {
        if (scale == 2) builder.append('.');
        long c = scaled / factor % 10;
        factor /= 10;
        builder.append((char) ('0' + c));
        scale--;
    }

    String newVal = builder.toString();
    DecimalFormatSymbols dfs = new DecimalFormatSymbols();

    char defDecSeparator = dfs.getDecimalSeparator();

    if ('.' != defDecSeparator) {
        return newVal.replace('.', defDecSeparator);
    }
    return newVal;
}

static String format_Naive(double value) {

    String val = Double.toString(value);

    int dotIndex = val.indexOf('.') + 1;
    int charsAfterDot = val.length() - dotIndex;

    if (charsAfterDot < 2) {
        val += "00";
    }

    // decimal point with a current locale
    DecimalFormatSymbols dfs = new DecimalFormatSymbols();

    char defDecSeparator = dfs.getDecimalSeparator();

    if ('.' != defDecSeparator) {
        return val.substring(0, dotIndex + 2).replace('.', defDecSeparator);
    }
    return val.substring(0, dotIndex + 2);
}

public static void main(String[] args) {

    for (int i = 1; i < 1000; i++) {
        double d = (22.4D / i)+i;
        formatUsingDecimalFormat(d);
        format_Naive(d);
        formatBy_Peter_Lawrey(d);
    }

    long s, e;

    //
    // DecimalFormat
    //
    s = System.currentTimeMillis();
    for (int i = 1; i < 100_000; i++) {
        formatUsingDecimalFormat((22.4D / i)+i);
    }
    e = System.currentTimeMillis();

    System.out.println((e - s) + " ms.");

    //
    // Naive
    //
    s = System.currentTimeMillis();
    for (int i = 1; i < 100_000; i++) {
        format_Naive((22.4D / i)+i);
    }
    e = System.currentTimeMillis();

    System.out.println((e - s) + " ms.");

    //
    // Peter_Lawrey
    //
    s = System.currentTimeMillis();
    for (int i = 1; i < 100_000; i++) {
        formatBy_Peter_Lawrey((22.4D / i)+i);
    }
    e = System.currentTimeMillis();

    System.out.println((e - s) + " ms.");

}

输出:

422 ms.
66 ms.
48 ms.
相关问题