开发者

java doesn't allow runtime-selectable-width format strings?

I need a way to print a number as hex, as a zero-padded string of width N, where N is selectable at runtime.

This doesn't work:

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

because evidently Java doesn't support the C-style use of %* f开发者_运维问答or runtime-selectable width format strings.

Any suggestions for an alternative?


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

:wrysmile:


@fd also with printf

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

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


Use an appropriate NumberFormat.

EDIT

This is plain wrong..

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜