tc39/proposal-intl-numberformat-v3

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.

sffc commented

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!

sffc commented

2021-02-11: We will add this to the proposal as signDisplay: "negative".

sffc commented

This is added to the README as of #28. It will be added to the spec draft in #29, which will then unblock implementations. This issue will be closed automatically when #28 is merged to reflect that it is part of the proposal.