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

How does JavaScript handle modulo? - Stack Overflow

programmeradmin0浏览0评论

I was wondering how JavaScript handles modulo. For example, what would JavaScript evaluate 47 % 8 as? I can’t seem to find any documentation on it, and my skills on modulo aren’t the best.

I was wondering how JavaScript handles modulo. For example, what would JavaScript evaluate 47 % 8 as? I can’t seem to find any documentation on it, and my skills on modulo aren’t the best.

Share Improve this question edited Sep 2, 2019 at 20:38 Sebastian Simon 19.6k8 gold badges61 silver badges84 bronze badges asked Jan 11, 2013 at 4:47 Elias BenevedesElias Benevedes 3911 gold badge9 silver badges28 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 3

Exactly as every language handles modulo: The remainder of X / Y.

47 % 8 == 7

Also if you use a browser like Firefox + Firebug, Safari, Chrome, or even IE8+ you could test such an operation as quickly as hitting F12.

Javascript's modulo operator returns a negative number when given a negative number as input (on the left side).

14 % 5 // 4
15 % 5 // 0
-15 % 5 // -0
-14 % 5 // -4

(Note: negative zero is a distinct value in JavaScript and other languages with IEEE floats, but -0 === 0 so you usually don't have to worry about it.)

If you want a number that is always between 0 and a positive number that you specify, you can define a function like so:

function mod(n, m) {
    return ((n % m) + m) % m;
}
mod(14, 5) // 4
mod(15, 5) // 4
mod(-15, 5) // 0
mod(-14, 5) // 1

Modulo should behave like you expect. I expect.

47 % 8 == 7

Fiddle Link

TO better understand modulo here is how its built;

function modulo(num1, num2) {
    if (typeof num1 != "number" || typeof num2 != "number"){
      return NaN
    }
    var num1isneg=false
     if (num1.toString().includes("-")){
      num1isneg=true
    }
      num1=parseFloat(num1.toString().replace("-",""))
      var leftover =parseFloat( ( parseFloat(num1/num2) - parseInt(num1/num2)) *num2)
      console.log(leftover)
            if (num1isneg){
              var z = leftover.toString().split("")
              z= ["-", ...z]
              leftover = parseFloat(z.join(""))
            }
            return leftover
}
发布评论

评论列表(0)

  1. 暂无评论