Nick
Nick

Reputation: 177

Convert a number to a String with exactly 2 decimal places

I am currently using the static String method String.format(String, Object) to format a string which represents a number.

I am truncating the string so that there is only two digits after the decimal place.

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

I would like to know how to go about getting the formatted string to have exactly two decimal places even if it is a whole number or doesn't have a tens significant digit.

Upvotes: 3

Views: 2106

Answers (3)

devops
devops

Reputation: 9179

I know, it is not realy important... but just my 2 cents about performance:

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.");

}

Output:

422 ms.
66 ms.
48 ms.

Upvotes: 0

Jimmysnn
Jimmysnn

Reputation: 593

This is an example:

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);

Upvotes: 0

Marlon Bernardes
Marlon Bernardes

Reputation: 13853

Of course you could use String.format for that, but why don't you just use DecimalFormat, which was built specifically for formatting numbers as Strings?

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

Upvotes: 8

Related Questions