简体   繁体   中英

Java String new line with specific logic and without string format

The following code:

String a = "100.00";
String b = "10.00";
String c=  "5.00";

String value = a+ "\n"+ b +"\n" +c;
System.out.println(value);

Prints:

100.00
10.00
5.00

I need output in a format where decimal point position will be fixed without using any string format library (with logic):

100.00
 10.00
  5.00 

Variable values are coming from the database and requirement is to show values with the decimal point in the same position with values vertically.

Here's an example using streams; probably could be more efficient but I was having fun.

It assumes all have 2 decimals as you showed, just FYI; that could be modified though.

String a = "100.00";
String b = "10.00";
String c=  "5.00";

List<String> strings = Arrays.asList(a, b, c);
final int maxLen = strings.stream().map(String::length).reduce(Math::max).get();

strings.forEach(s -> {
    System.out.println(Stream.generate(() -> " ").limit(maxLen - s.length()).collect(Collectors.joining()) + s);
});

Results:

100.00
 10.00
  5.00

I also put pthe 3 examples into a list so it would work on an arbitrary number of elements.

Without Java 8

String a = "100.00";
String b = "10.00";
String c =  "5.00";

List<String> strings = Arrays.asList(a, b, c);

int maxLen = -1;
for (String s : strings) maxLen = Math.max(maxLen, s.length());
for (String s : strings) {
    String spaces = "";
    for (int i = 0; i < maxLen - s.length(); ++i) {
        spaces += " ";
    }
    System.out.println(spaces += s);
}

I don't know what 'don't use any String format library' means specifically, but... now we get into a semantic argument as to what 'library' means. You're formatting a string. If I take your question on face value you're asking for literally the impossible: How does one format a string without formatting a string?

I'm going to assume you meant: Without adding a third party dependency.

In which case, if you have doubles (or BigDecimal or float ) as input:

String.format("%6.2f", 100.00);
String.format("%6.2f", 10.00);
String.format("%6.2f", 5.00);

(6? Yes; 6! The 6 is the total # of characters to print at minimum. You want 3 digits before the separator, a separator, and 2 digits after, that's a grand total of 6, hence the 6.)

If you have strings as input, evidently you are asking to right-justify them? Well, you can do that:

String.format("%6s", "100.00");
String.format("%6s", "10.00");
String.format("%6s", "5.00");

NB: For convenience, System.out.printf("%6s\\n", "100.0"); is short for System.out.println(String.format("%6s", "100.0"));

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