3

I'm getting formatting issues with numeral.js when rounding to the nearest negative 100th.

Thoughts on why it's putting the zero before the dollar sign for the zero value?

FIDDLE

var num1 = numeral(-0.006).format('$0,0.00');
var num2 = numeral(-0.002).format('$0,0.00');

document.getElementById("num1").innerHTML = num1;
document.getElementById("num2").innerHTML = num2;
Shawn
  • 4,758
  • 1
  • 20
  • 29
Kirk Ross
  • 6,413
  • 13
  • 61
  • 104

1 Answers1

2

Could be a bug in numeral.js. Regardless, if this is what you are attempting to do, you can drop your dependency for numeral.js and just use plain Javascript Math and toLocaleString() to deal with this.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

https://jsfiddle.net/qL41jg1x/

function toUSCurrency(x) {
   var n = Math.round(x*100)/100
   return n.toLocaleString(
            'en-US' , 
            { 
                style: 'currency' , 
                currency: 'USD' ,
                minimumFractionDigits: 2 ,
                maximumFractionDigits: 2 
             }
        ) ;
}

document.getElementById("num1").innerHTML = toUSCurrency(-0.006);
document.getElementById("num2").innerHTML = toUSCurrency(-0.002);
document.getElementById("num3").innerHTML = toUSCurrency(-10000000.002);
document.getElementById("num4").innerHTML = toUSCurrency(10000000.002);

NOTES: 1) Math.round() can get into the floating point nature of numbers if you have to deal with very large decimals.

2) toLocaleString() seems to be supported by all current major browsers. https://caniuse.com/#feat=internationalization

Shawn
  • 4,758
  • 1
  • 20
  • 29
  • Also note that comments on numeral.js point to it being abandoned. https://github.com/adamwdraper/Numeral-js – Shawn Feb 07 '18 at 23:41
  • In the Issues, someone asks if the project was abandoned with no response from the maintainer. https://github.com/adamwdraper/Numeral-js/issues/566 Plus there are 91 pull requests and the last update was 11 months ago. It might be worthwhile to fork the project, merge in the pull requests, and see if any of them fix the issue. But again, if you aren't using numeric.js for anything else, I'd say get rid of the dependency and use vanilla js. – Shawn Feb 08 '18 at 04:16
  • One other note: in Javascript, +0 and -0 are different (rounding of -0.002 to -0.00). I believe this is dealt with in `Math.round(x*100)/100`, in that it turns -0 into just 0. This gives you $0.00 instead of -$0.00. – Shawn Feb 08 '18 at 04:21