简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM