MikeMcl / bignumber.js

A JavaScript library for arbitrary-precision decimal and non-decimal arithmetic
http://mikemcl.github.io/bignumber.js
MIT License
6.68k stars 742 forks source link

inconsistency of `toFormat` result with negative zero #288

Closed Elinia closed 3 years ago

Elinia commented 3 years ago

toFormat provides different results with negative zero, is it an expected behavior?

console.log(new BigNumber("-0.1").toFormat(0)); // '-0'
console.log(new BigNumber("-0").toFormat(0)); // '0'

I found this issue when trying to support negative decimal places with something like:

function formatNumber(value, decimalPlaces, roundingMode, format) {
  var multiplier = new BigNumber(10).pow(decimalPlaces)
  return new BigNumber(value)
    .times(multiplier)
    .dp(0, roundingMode)
    .div(multiplier)
    .toFormat(Math.max(decimalPlaces, 0), roundingMode, format)
}
MikeMcl commented 3 years ago

Yes, it intentionally matches the behaviour of toFixed with primitive numbers:

console.log( (-0.1).toFixed(0) );    // '-0'
console.log( (-0).toFixed(0) );      // '0'

I'll consider supporting negative decimal places here.

Elinia commented 3 years ago

Thanks for the kindly reply!