最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - IE browser not supporting Math.trunc() - Stack Overflow

programmeradmin3浏览0评论

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");
}

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");
}
Share Improve this question edited Feb 26, 2020 at 21:47 norbitrial 15.2k10 gold badges39 silver badges64 bronze badges asked Feb 25, 2020 at 20:29 DevDev 231 silver badge3 bronze badges 4
  • That's true, see on MDN - IE is not supported: developer.mozilla/en-US/docs/Web/JavaScript/Reference/… – norbitrial Commented Feb 25, 2020 at 20:30
  • 1 You'll need to use a polyfill to provide support in IE – user47589 Commented Feb 25, 2020 at 20:31
  • Yeah polyfills are the way to go! Or have your own implementation of it. – tschaka1904 Commented Feb 25, 2020 at 20:36
  • Would this work for you? – Yevhen Horbunkov Commented Feb 25, 2020 at 21:21
Add a ment  | 

3 Answers 3

Reset to default 11

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.

Yes, IE does not support Math.trunc, or many other features. See the MDN browser patibility 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);
    };
}

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);
}
发布评论

评论列表(0)

  1. 暂无评论