Domanda

Come posso arrotondare un numero in JavaScript?

math.round () non funziona perché lo arrotonda al decimale più vicino.

Non sono sicuro che esista un modo migliore per farlo se non quello di separarlo in punto decimale per mantenere il primo bit. Ci deve essere ...

È stato utile?

Soluzione

Math.floor()

è la risposta.

Altri suggerimenti

Rotonda verso l'infinito negativo - Math.floor()

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

Arrotondamento verso zero - in genere chiamato Truncate () , ma non supportato da JavaScript - può essere emulato utilizzando Math.ceil () per numeri negativi e Math.floor () per numeri positivi.

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

Math.floor () funzionerà, ma è molto lento rispetto all'utilizzo di un'operazione OR bit a bit:

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

MODIFICA Math.floor () è non più lento dell'uso del | operatore. Grazie a Jason S per aver controllato il mio lavoro.

Ecco il codice che ho usato per testare:

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

Puoi provare a usare questa funzione se devi arrotondare per eccesso a un numero specifico di cifre decimali

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

esempi

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

Per arrotondare per difetto all'infinito negativo, usare:

rounded=Math.floor(number);

Per arrotondare per difetto a zero (se il numero può arrotondare a un numero intero a 32 bit compreso tra -2147483648 e 2147483647), utilizzare:

rounded=number|0;

Per arrotondare per difetto a zero (per qualsiasi numero), utilizzare:

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

L'arrotondamento di un numero verso 0 può essere fatto sottraendo la parte frazionata firmata numero% 1 :

rounded = number - number % 1;

Come Math.floor (arrotonda verso -Infinity ) questo metodo è perfettamente accurato.

Esistono differenze nella gestione di -0 , + Infinity e -Infinity sebbene:

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)

Oggi stavo armeggiando con il codice di qualcun altro e ho trovato quanto segue che sembra arrotondare per difetto:

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

Per ulteriori informazioni sullo spostamento a destra di propagazione dei segni (> >) consulta Operatori bit per bit MDN

Mi ci è voluto un po 'per capire cosa stesse facendo: D

Ma come evidenziato sopra, Math.floor () funziona e sembra più leggibile secondo me.

Devi mettere -1 per arrotondare la metà in basso e successivamente moltiplicare per -1 come nell'esempio qui sotto.

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

Ecco math.floor utilizzato in un semplice esempio. Questo potrebbe aiutare un nuovo sviluppatore a farsi un'idea di come usarlo in una funzione e di cosa fa. Spero che sia d'aiuto!

<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>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top