smuggledPancakes
smuggledPancakes

Reputation: 10323

Trouble with Java DecimalFormat

How would I create a DecimalFormat that would only have seven digits total and also have it favor the left hand side of the number.

For example: 1234.5678 would transform to 1234.567 1.2345678 would transform to 1.234567 1234567.8 would transform to 1234567

Upvotes: 0

Views: 272

Answers (2)

Bohemian
Bohemian

Reputation: 424993

DecimalFormat can't do what you want, but I think this is more a String question. Once you have your formatted decimal, you can do this:

String number = "123.45678"; // output from decimal format

number = number.substring(0, 7 + (number.contains(".") ? 1 : 0)).replaceAll("\\.$", "");

This truncates the string length to 7, or 8 if a decimal point is found (then removing any trailing decimal points), which is what you require.

Here's some test code:

private static String format(String number) {
    return number.substring(0, 7 + (number.contains(".") ? 1 : 0)).replaceAll("\\.$", "");
}

public static void main(String[] args) {
    System.out.println(format("1234567"));
    System.out.println(format("1.2345678"));
    System.out.println(format("1234.5678"));
    System.out.println(format("1234567.8"));
    System.out.println(format(".12345678"));
}

Output:

1234567
1.234567
1234.567
1234567

    .1234567

Upvotes: 2

sperumal
sperumal

Reputation: 1519

I don't think you do this kind of formatting with DecimalFormat, but you perform String manipulation

double d = 1234567.8;
System.out.println(new StringBuilder()
     .append(d).substring(0, 8)
     .replaceAll("\\.$", "") // to remove last decimal
     .toString());

Upvotes: 2

Related Questions