javascriptbrowser

Function Number.prototype.toLocaleString() returns negative 0


Below code returns negative 0 instead of 0. Is there a way to fix this issue?

const x=-0.01;
console.log(
  x.toLocaleString('en-US',{minimumFractionDigits:0,maximumFractionDigits:0})
)


Solution

  • You can set the signDisplay option to exceptZero or negative:

    const x = -0.01;
    const y = x.toLocaleString('en-US',{
      minimumFractionDigits: 0,
      maximumFractionDigits: 0,
      signDisplay: 'exceptZero'
    });
    
    console.log(y);

    Note that using exceptZero will also add an explicit sign for positive numbers, while using negative will not.