如何在Javascript中舍入一个数字?

时间:2009-09-16 23:06:42

标签: javascript math rounding

如何在JavaScript中舍入数字?

math.round()不起作用,因为它将其舍入到最接近的小数。

我不确定是否有更好的方法可以做到这一点,而不是在保持第一位的小数点上将它分开。必须有......

11 个答案:

答案 0 :(得分:396)

Math.floor()

就是答案。

答案 1 :(得分:58)

走向负无穷大 - Math.floor()

+3.5 => +3.0
-3.5 => -4.0

归零(通常称为Truncate(),但不受JavaScript支持 - 可以使用Math.ceil()表示负数,Math.floor()表示正数。

+3.5 => +3.0 using Math.floor()
-3.5 => -3.0 using Math.ceil()

答案 2 :(得分:23)

Math.floor()可以使用,但与使用按位OR操作相比,速度非常慢:

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

编辑 Math.floor() 比使用| <运营商。感谢Jason S检查我的工作。

以下是我用来测试的代码:

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

答案 3 :(得分:21)

如果需要向下舍入到特定数量的小数位,可以尝试使用此功能

function roundDown(number, decimals) {
    decimals = decimals || 0;
    return ( Math.floor( number * Math.pow(10, decimals) ) / Math.pow(10, decimals) );
}

实施例

alert(roundDown(999.999999)); // 999
alert(roundDown(999.999999, 3)); // 999.999
alert(roundDown(999.999999, -1)); // 990

答案 4 :(得分:6)

要向负向无穷大舍入,请使用:

rounded=Math.floor(number);

向下舍入为零(如果数字可以舍入到-2147483648和2147483647之间的32位整数),请使用:

rounded=number|0;

要向下舍入为零(对于任何数字),请使用:

if(number>0)rounded=Math.floor(number);else rounded=Math.ceil(number);

答案 5 :(得分:5)

number舍入0可以通过减去已签名的小数部分number % 1来完成:

rounded = number - number % 1;

Math.floor一样(向-Infinity方向转)这种方法非常准确。

-0+Infinity-Infinity的处理方式存在差异:

Math.floor(-0) => -0
-0 - -0 % 1    => +0

Math.floor(Infinity)    => Infinity
Infinity - Infinity % 1 => NaN

Math.floor(-Infinity)     => -Infinity
-Infinity - -Infinity % 1 => NaN

答案 6 :(得分:3)

Math.floor(1+7/8)

答案 7 :(得分:3)

今天正在使用别人的代码进行调整,并发现以下内容似乎已经完成:

var dec = 12.3453465,
int = dec >> 0; // returns 12

有关Sign-propagating右移(&gt;&gt;)的更多信息,请参阅MDN Bitwise Operators

我花了一段时间才弄清楚这是做什么的:D

但正如上面所强调的那样,Math.floor()在我看来看起来更具可读性。

答案 8 :(得分:0)

你需要把-1放到下半轮然后再乘以-1,就像下面的示例一样。

<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>

答案 9 :(得分:0)

在一个简单的示例中使用math.floor。这可能有助于新开发人员了解如何在函数中使用它以及它做什么。希望对您有帮助!

<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>

答案 10 :(得分:0)

这是我发现可靠的最佳解决方案。

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

信用至:Jack L Moore's blog