【发布时间】:2010-11-28 23:44:40
【问题描述】:
如何在 JavaScript 中对数字进行四舍五入?
math.round() 不起作用,因为它会将其四舍五入到最接近的小数。
我不确定是否有更好的方法来做到这一点,而不是在保留第一位的小数点处将其分开。一定有……
【问题讨论】:
-
向零取整还是向负无穷取整?
标签: javascript math rounding
如何在 JavaScript 中对数字进行四舍五入?
math.round() 不起作用,因为它会将其四舍五入到最接近的小数。
我不确定是否有更好的方法来做到这一点,而不是在保留第一位的小数点处将其分开。一定有……
【问题讨论】:
标签: javascript math rounding
使用Math.floor() 是一种方法。
更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor
【讨论】:
Math.floor(1+7/8)
【讨论】:
Math.floor() 可以工作,但与使用按位 OR 操作相比非常慢:
var rounded = 34.923 | 0;
alert( rounded );
//alerts "34"
EDIT 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 );
【讨论】:
| 转换为 32 位整数,截断; Math.floor 向下舍入。 jsfiddle.net/minitech/UVG2w
向负无穷舍入 - Math.floor()
+3.5 => +3.0
-3.5 => -4.0
可以使用Math.trunc() 向零舍入。较旧的浏览器不支持此功能。如果需要支持这些,可以使用Math.ceil() 表示负数,Math.floor() 表示正数。
+3.5 => +3.0 using Math.floor()
-3.5 => -3.0 using Math.ceil()
【讨论】:
x | 0获得与四舍五入相同的效果。
今天正在摆弄别人的代码,发现以下内容似乎也很糟糕:
var dec = 12.3453465,
int = dec >> 0; // returns 12
有关符号传播右移(>>)的更多信息,请参阅MDN Bitwise Operators
我花了一段时间才弄清楚这是在做什么:D
但正如上面强调的那样,Math.floor() 在我看来是有效的并且看起来更具可读性。
【讨论】:
如果需要四舍五入到特定的小数位数,可以尝试使用此功能
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
【讨论】:
要向下舍入到负无穷,请使用:
rounded=Math.floor(number);
要向下舍入为零(如果数字可以舍入为介于 -2147483648 和 2147483647 之间的 32 位整数),请使用:
rounded=number|0;
要向下舍入到零(对于任何数字),请使用:
if(number>0)rounded=Math.floor(number);else rounded=Math.ceil(number);
【讨论】:
将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
【讨论】:
您需要将 -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>
【讨论】:
这是 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>
【讨论】:
这是我发现的可靠工作的最佳解决方案。
function round(value, decimals) {
return Number(Math.floor(parseFloat(value + 'e' + decimals)) + 'e-' + decimals);
}
【讨论】: