IE browser not supporting Math.trunc()

Viewed 2565

The below code is working fine in Chrome, but in IE browser I am seeing the below console error:

object does not support property or method 'trunc'

Code:

var Days = (new Date(date1) - new Date(date2)) / 50;
if (Math.trunc(Days) > 45)) {
 alert("it should be less than 45 days");
}
3 Answers

Math.trunc is not supported in IE as MDN states, please read here.

Instead you could use polifylls:

if (!Math.trunc) {
    Math.trunc = function (v) {
        return v < 0 ? Math.ceil(v) : Math.floor(v);
    };
}

Hope that clarifies.

It isn't built into the browser. You can use the following polyfill

Math.trunc = Math.trunc || function(x) {
  if (isNaN(x)) {
    return NaN;
  }
  if (x > 0) {
    return Math.floor(x);
  }
  return Math.ceil(x);
};

Update

After seeing a much neater version from @norbitrial this can be expressed even more succinctly as

Math.trunc = Math.trunc || function(x) {
    return x < 0 ? Math.ceil(x) : Math.floor(x);
}

Yes, IE does not support Math.trunc, or many other features. See the MDN browser compatibility table.

Your options are do the logic that .trunc is doing your self, or use an existing polyfill. Either way it would end up looking something like:

if (!Math.trunc) {
    Math.trunc = function (v) {
        return v < 0 ? Math.ceil(v) : Math.floor(v);
    };
}
Related