I want to format a message like "Data transfer of 1.0 KiB took 1:32 hours". But I need both byte count and time duration formatted and localized. I found several ideas how to format the byte count, time duration seems fine. But then it comes the localization and my home-grown code becomes excessive. I am looking for any ideas how such formatting could be implemented with the help of ICU library.
Asked
Active
Viewed 668 times
2 Answers
2
You can simply use the Java MessageFormat
which allows you to format different java types to strings; this format should do what you want
final MessageFormat format = new MessageFormat("Data transfer of {0,number,0.0} KiB took {1}:{2} hours");
Usage would be
final String formatted = format.format(new Object[]{amountTransferred, hours, minutes});
Where amountTransferred
is a double
or float
or BigDecimal
, hours
and minutes
are integer types.
There is already a post on how to format a number of minutes to HH:mm
if you need to do that separately.

Community
- 1
- 1

Boris the Spider
- 59,842
- 6
- 106
- 166
-
Unfortunately it is not so simple. Imagine the byte count is 1000000 e.g. 1MiB. So I need it formated like 1.0 MiB. And imagine this message is localized in Chinise and MiB should be some Chinise symbol. – Max Mar 09 '13 at 17:47
-
I see what you want - this answer won't do that in its entirety. Maybe some kind soul has a better idea... – Boris the Spider Mar 09 '13 at 18:03
0
ICU has both compact decimals for units (1.0 MiB) and duration formats now. This is a great question, I don't think msgformat supports this natively now.
What you could do is to just use the pattern {0,number}
without KiB as in Boris' response, but then call format.setFormat(0,...)
to replace the number formatter with a CompactDecimalFormat or with a unit formatter.

Steven R. Loomis
- 4,228
- 28
- 39