开发者

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

开发者 https://www.devze.com 2023-02-02 04:07 出处:网络
I need a way to print a number as hex, as a zero-padded string of width N, where N is selectable at runtime.

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

精彩评论

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