How can I round down a number in Javascript?

前端 未结 11 1358
感动是毒
感动是毒 2020-11-29 23:27

How can I round down a number in JavaScript?

math.round() doesn\'t work because it rounds it to the nearest decimal.

I\'m not sure if there is

相关标签:
11条回答
  • 2020-11-29 23:53

    Here is math.floor being used in a simple example. This might help a new developer to get an idea how to use it in a function and what it does. Hope it helps!

    <script>
    
    var marks = 0;
    
    function getRandomNumbers(){    //  generate a random number between 1 & 10
        var number = Math.floor((Math.random() * 10) + 1);
        return number;
    }
    
    function getNew(){  
    /*  
        This function can create a new problem by generating two random numbers. When the page is loading as the first time, this function is executed with the onload event and the onclick event of "new" button.
    */
    document.getElementById("ans").focus();
    var num1 = getRandomNumbers();
    var num2 = getRandomNumbers();
    document.getElementById("num1").value = num1;
    document.getElementById("num2").value = num2;
    
    document.getElementById("ans").value ="";
    document.getElementById("resultBox").style.backgroundColor = "maroon"
    document.getElementById("resultBox").innerHTML = "***"
    
    }
    
    function checkAns(){
    /*
        After entering the answer, the entered answer will be compared with the correct answer. 
            If the answer is correct, the text of the result box should be "Correct" with a green background and 10 marks should be added to the total marks.
            If the answer is incorrect, the text of the result box should be "Incorrect" with a red background and 3 marks should be deducted from the total.
            The updated total marks should be always displayed at the total marks box.
    */
    
    var num1 = eval(document.getElementById("num1").value);
    var num2 = eval(document.getElementById("num2").value);
    var answer = eval(document.getElementById("ans").value);
    
    if(answer==(num1+num2)){
        marks = marks + 10;
        document.getElementById("resultBox").innerHTML = "Correct";
        document.getElementById("resultBox").style.backgroundColor = "green";
        document.getElementById("totalMarks").innerHTML= "Total marks : " + marks;
    
    }
    
    else{
        marks = marks - 3;
        document.getElementById("resultBox").innerHTML = "Wrong";
        document.getElementById("resultBox").style.backgroundColor = "red";
        document.getElementById("totalMarks").innerHTML = "Total Marks: " + marks ;
    }
    
    
    
    
    }
    
    </script>
    </head>
    
    <body onLoad="getNew()">
        <div class="container">
            <h1>Let's add numbers</h1>
            <div class="sum">
                <input id="num1" type="text" readonly> + <input id="num2" type="text" readonly>
            </div>
            <h2>Enter the answer below and click 'Check'</h2>
            <div class="answer">
                <input id="ans" type="text" value="">
            </div>
            <input id="btnchk" onClick="checkAns()" type="button" value="Check" >
            <div id="resultBox">***</div>
            <input id="btnnew" onClick="getNew()" type="button" value="New">
            <div id="totalMarks">Total marks : 0</div>  
        </div>
    </body>
    </html>
    
    0 讨论(0)
  • 2020-11-29 23:54

    You need to put -1 to round half down and after that multiply by -1 like the example down bellow.

    <script type="text/javascript">
    
      function roundNumber(number, precision, isDown) {
        var factor = Math.pow(10, precision);
        var tempNumber = number * factor;
        var roundedTempNumber = 0;
        if (isDown) {
          tempNumber = -tempNumber;
          roundedTempNumber = Math.round(tempNumber) * -1;
        } else {
          roundedTempNumber = Math.round(tempNumber);
        }
        return roundedTempNumber / factor;
      }
    </script>
    
    <div class="col-sm-12">
      <p>Round number 1.25 down: <script>document.write(roundNumber(1.25, 1, true));</script>
      </p>
      <p>Round number 1.25 up: <script>document.write(roundNumber(1.25, 1, false));</script></p>
    </div>
    
    0 讨论(0)
  • 2020-11-29 23:57

    Using Math.floor() is one way of doing this.

    More information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor

    0 讨论(0)
  • 2020-11-29 23:58

    This was the best solution I found that works reliably.

    function round(value, decimals) {
        return Number(Math.floor(parseFloat(value + 'e' + decimals)) + 'e-' + decimals);
     }
    

    Credit to: Jack L Moore's blog

    0 讨论(0)
  • 2020-11-30 00:03

    Rounding a number towards 0 can be done by subtracting its signed fractional part number % 1:

    rounded = number - number % 1;
    

    Like Math.floor (rounds towards -Infinity) this method is perfectly accurate.

    There are differences in the handling of -0, +Infinity and -Infinity though:

    Math.floor(-0) => -0
    -0 - -0 % 1    => +0
    
    Math.floor(Infinity)    => Infinity
    Infinity - Infinity % 1 => NaN
    
    Math.floor(-Infinity)     => -Infinity
    -Infinity - -Infinity % 1 => NaN
    
    0 讨论(0)
  • 2020-11-30 00:05

    Math.floor() will work, but it's very slow compared to using a bitwise OR operation:

    var rounded = 34.923 | 0;
    alert( rounded );
    //alerts "34"
    

    EDIT Math.floor() is not slower than using the | operator. Thanks to Jason S for checking my work.

    Here's the code I used to test:

    var a = [];
    var time = new Date().getTime();
    for( i = 0; i < 100000; i++ ) {
        //a.push( Math.random() * 100000  | 0 );
        a.push( Math.floor( Math.random() * 100000 ) );
    }
    var elapsed = new Date().getTime() - time;
    alert( "elapsed time: " + elapsed );
    
    0 讨论(0)
提交回复
热议问题