Java doesn't allow using runtime-selectable-width format strings?

I need a way to print the number as hex, as a zero line of width N, where N can be selected at runtime.

This does not work:

System.out.println(String.format("%*x", 4, 0x123))

because it’s obvious that Java does not support Using C% in% * for width format strings selected at runtime .

Any suggestions for an alternative?

+3
source share
3 answers
int width = 4;
String format = "%" + width + "x";
System.out.println(String.format(format, 0x123));

: wrysmile:

+6
source

@fd also with printf

int width = 4;
String format = "%" + width + "x";
System.out.printf(format, 0x123);

System.out.printf("%4x", 0x123);
+1
source

Use the appropriate NumberFormat.

EDIT

It is not right.

-2
source

Source: https://habr.com/ru/post/1783459/


All Articles