Pregunta

¿Cómo puedo redondear un número en JavaScript?

math.round () no funciona porque lo redondea al decimal más cercano.

No estoy seguro de si hay una mejor manera de hacerlo que no sea separarlo en el punto decimal para mantener el primer bit. Debe haber ...

¿Fue útil?

Solución

Math.floor()

es la respuesta.

Otros consejos

Redondear hacia el infinito negativo - Math.floor()

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

Redondear hacia cero, generalmente llamado Truncate () , pero no compatible con JavaScript, puede emularse usando Math.ceil () para números negativos y Math.floor () para números positivos.

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

Math.floor () funcionará, pero es muy lento en comparación con el uso de una operación bitcode OR :

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

EDITAR Math.floor () es no más lento que usar el | operador. Gracias a Jason S por revisar mi trabajo.

Aquí está el código que solía probar:

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

Puede intentar usar esta función si necesita redondear a un número específico de decimales

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

ejemplos

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

Para redondear hacia el infinito negativo, use:

rounded=Math.floor(number);

Para redondear hacia abajo a cero (si el número puede redondearse a un entero de 32 bits entre -2147483648 y 2147483647), use:

rounded=number|0;

Para redondear hacia cero (para cualquier número), use:

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

El redondeo de un número hacia 0 se puede hacer restando su parte fraccionada con signo number% 1 :

rounded = number - number % 1;

Al igual que Math.floor (se redondea hacia -Infinity ), este método es perfectamente preciso.

Existen diferencias en el manejo de -0 , + Infinity y -Infinity aunque:

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

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

Math.floor(-Infinity)     => -Infinity
-Infinity - -Infinity % 1 => NaN
Math.floor(1+7/8)

Estaba jugando con el código de otra persona hoy y encontró lo siguiente que parece redondeado también:

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

Para obtener más información sobre el desplazamiento a la derecha de propagación de signos (> >) consulte Operadores MDN Bitwise

Me tomó un tiempo averiguar qué estaba haciendo: D

Pero como se destacó anteriormente, Math.floor () funciona y parece más legible en mi opinión.

Necesita poner -1 para redondear la mitad hacia abajo y luego multiplicar por -1 como el ejemplo abajo abajo.

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

Aquí se usa math.floor en un ejemplo simple. Esto podría ayudar a un nuevo desarrollador a tener una idea de cómo usarlo en una función y qué hace. ¡Espero que ayude!

<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>
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top