简体   繁体   中英

numeral.js - negative number rounding/formatting issue

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM