Pergunta

Como posso rodada para baixo um número em JavaScript?

math.round() não funciona porque arredonda-lo para o decimal mais próximo.

Eu não tenho certeza se há uma maneira melhor de fazê-lo que não quebrar o diferencia no ponto decimal em manter o primeiro bit. Deve haver ...

Foi útil?

Solução

Math.floor()

é a resposta.

Outras dicas

Round para o infinito negativo - Math.floor()

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

Round para zero - geralmente chamado Truncate(), mas não é suportado pelo JavaScript -. Pode ser emulado usando Math.ceil() para números negativos e Math.floor() para números positivos

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

Math.floor() vai funcionar, mas é muito lento em comparação ao uso de uma operação bit a bit OR:

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

Editar Math.floor() não mais lento do que usando o | operador. Graças a Jason S para verificar meu trabalho.

Aqui está o código que usei para testar:

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

Você pode tentar usar esta função, se você precisa para baixo e volta para um número específico de casas decimais

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

exemplos

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

Para baixo rodada para o infinito negativo, use:

rounded=Math.floor(number);

Para baixo volta para zero (se o número pode arredondar para um número inteiro de 32 bits entre -2147483648 e 2147483647), use:

rounded=number|0;

Para baixo volta para zero (para qualquer número), use:

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

Completando um number direção 0 pode ser feito subtraindo sua number % 1 parte fracionária assinado:

rounded = number - number % 1;

Como Math.floor (rodadas no sentido -Infinity) este método é perfeitamente precisa.

Existem diferenças no manejo de -0, +Infinity e -Infinity entanto:

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)

Foi mexer rodada com código de alguma outra pessoa hoje e encontrou o seguinte que parece rodadas para baixo também:

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

Para obter mais informações sobre o deslocamento para a direita-propagação Sign (>>) consulte MDN bit a bit Operadores

Levei um tempo para descobrir o que isso estava fazendo: D

Mas, como destacado acima, Math.floor () funciona e parece mais legível na minha opinião.

Você precisa colocar -1 a metade rodada para baixo e depois multiplique por -1 como o exemplo para baixo abaixo.

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

Aqui está Math.floor sendo usada em um exemplo simples. Isto pode ajudar um novo desenvolvedor para ter uma idéia como usá-lo em uma função e que ele faz. Espero que ajude!

<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 em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top