Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

toLocaleString() for IE 8

Below is my JavaScript:

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

this gives result 123,456,789 in chrome. But IE 8 shows 123,456,789.00. Is there any workaround to restrict the addition of ".00" in IE?


FYI: I have already checked This which gives problem in Chrome and have searched around google with no use.

like image 714
Naveen Avatar asked Oct 22 '14 10:10

Naveen


2 Answers

// Following @RobG's comment I have altered and simplified to find any character that might be used as a decimal point (unless it's the first character)

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);
like image 135
Weather Vane Avatar answered Sep 29 '22 14:09

Weather Vane


You can test for the decimal separator and remove it and everything thereafter:

// 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'll need to change system settings to test thoroughly.

Edit

If you want to change the built–in toLocaleString, 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);
    }
  }());
}

This will modify the built–in toLocaleString only if it adds decimal places to integers.

like image 40
RobG Avatar answered Sep 29 '22 15:09

RobG