signDisplay: missing option for a reasonable use-case
pspraveenkr opened this issue ยท 5 comments
Use-case:
I'd like to round negative values but I don't want -0
to be formatted into a string with "minus" sign i.e. I prefer "0"
instead of "-0"
For example:
const formatter = new Intl.NumberFormat("en", {
maximumFractionDigits: 1
});
console.log(formatter.format(-0.03));
// Returns: -0
// Desired result: 0
The proposed spec for signDisplay
supports these options: auto
, always
, never
and exceptZero
. But, none of them seem to produce the output desired for the use-case above - without compromising on something else.
exceptZero
comes close, but in addition to removing the minus sign from -0
, it also adds a plus sign to positive numbers (as expected) which is not desired for the use-case above.
var formatter = new Intl.NumberFormat("en", {
maximumFractionDigits: 1,
signDisplay: "exceptZero"
});
console.log(formatter.format(-0.03));
// Returns the desired result: 0 ๐
// but...
console.log(formatter.format(123));
// Returns: +123 ๐
// Desired result: 123
I found this table containing examples of signDisplay
options here: https://github.com/tc39/proposal-unified-intl-numberformat/blob/master/README.md#iii-sign-display. I was hoping to find an option that would produce -1 | 0 | 0 | 1 | NaN
, but such an option does not seem to exist.
Am I missing something? What is the recommendation for handling the use-case above?
Thank you.
Thanks for the feedback!
Maybe we could call this "onlyNegative"
?
In the mean time, you can do
class Formatter {
constructor(locale) {
this.negative = new Intl.NumberFormat(locale, { signDisplay: "exceptZero" });
this.positive = new Intl.NumberFormat(locale, { signDisplay: "auto" });
}
format(input) {
if (input < 0) return this.negative.format(input);
else return this.positive.format(input);
}
}
Maybe we could call this
"onlyNegative"
?
Yes, either "onlyNegative"
or just "negative"
would be suitable.
Thanks for the interim solution!
Upstream issue: https://unicode-org.atlassian.net/browse/ICU-21484
2021-02-11: We will add this to the proposal as signDisplay: "negative"
.