java - Best way to format based on multiple conditions in a MessageFormat - Stack Overflow

admin2025-04-21  2

When using MessageFormat I've noticed it's not easy to use more than one argument as a condition to format text. An example would be placing " and " between two values (e.g. like with durations: "1 hour and 20 minutes"), if and only if they are both non-zero. At two conditions, the only solution I've found is nested sub-formats and is fairly verbose:

"{0}{0,plural,=0{} other{{1,plural,=0{} other{ and }}}}{1}"

And introducing a third condition would make this even worse.

I would expect there to be a way to have a union of conditions. Theoretically something like:

"{0}{plural,0=0&1=0{} other{ and }}{1}"

Is there a better way to achieve this behavior while still only using MessageFormat? Even if using custom subformats or rules?

转载请注明原文地址:http://anycun.com/QandA/1745227559a90485.html