ToLocaleString () for IE 8

Below is my javascript

 var s = new Number(123456789);
 alert(s.toLocaleString("en-US"));

this gives a result 123,456,789in chrome. But IE 8 shows 123,456,789.00. Is there any work to limit adding ".00"in IE?

FYI: I already checked This , which gives the problem in Chrome, and searched around Google for no use.

+4
source share
2 answers

You can check the decimal separator and remove it and everything after that:

// Work out whether decimal separator is . or , for localised numbers
function getDecimalSeparator() {
  return /\./.test((1.1).toLocaleString())? '.' : ',';
}

// Round n to an integer and present
function myToLocaleInteger(n) {
  var re = new RegExp( '\\' + getDecimalSeparator() + '\\d+$');
  return Math.round(n).toLocaleString().replace(re,'');
}

// Test with a number that has decimal places
var n = 12345.99

console.log(n.toLocaleString() + ' : ' + myToLocaleInteger(n)); // 12,345.99 : 12,346

You will need to change the system settings in order to thoroughly test.

Edit

If you want to change the built-in toLocaleString function, try:

// Only modify if toLocaleString adds decimal places
if (/\D/.test((1).toLocaleString())) {

  Number.prototype.toLocaleString = (function() {

    // Store built-in toLocaleString
    var _toLocale = Number.prototype.toLocaleString;

    // Work out the decimal separator
    var _sep = /\./.test((1.1).toLocaleString())? '.' : ',';

    // Regular expression to trim decimal places
    var re = new RegExp( '\\' + _sep + '\\d+$');

    return function() {

      // If number is an integer, call built–in function and trim decimal places
      // if they're added
      if (parseInt(this) == this) {
        return _toLocale.call(this).replace(re,'');
      }

      // Otherwise, just convert to locale
      return _toLocale.call(this);
    }
  }());
}

toLocaleString, .

+2

// @RobG , ( )

var s = new Number(123456789);
var s1 = s.toLocaleString();
var p = new Number(Math.floor(s) + 0.1);    // similar value but decimal
var p1 = p.toLocaleString();
var index;
var point;
for (index=p1.length-1; index>0; index--) { // find decimal point in dummy
    point = p1.charAt(index);
    if (point < '0' || point > '9')
        break;
    }
if (index > 0) {
    index = s1.lastIndexOf(point);          // find last point in string
    if (index > 0)
        s1 = s1.slice(0, index);            // truncate decimal part
    }
alert(s1);
+1

All Articles