Как я могу округлить число в меньшую сторону в Javascript?

StackOverflow https://stackoverflow.com/questions/1435975

  •  07-07-2019
  •  | 
  •  

Вопрос

Как я могу округлить число в меньшую сторону в JavaScript?

math.round() не работает, потому что округляет значение до ближайшего десятичного знака.

Я не уверен, есть ли лучший способ сделать это, кроме как разбить его на десятичные дроби при сохранении первого бита.Должно быть...

Это было полезно?

Решение

Math.floor()

ответ.

Другие советы

Округление до отрицательной бесконечности - 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()

Math.floor () будет работать, но это очень медленно по сравнению с использованием побитовой операции ИЛИ :

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

РЕДАКТИРОВАТЬ Math.floor () не медленнее, чем с помощью | оператор. Спасибо Джейсону С. за проверку моей работы.

Вот код, который я использовал для проверки:

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

Вы можете попробовать использовать эту функцию, если вам нужно округлить значение в меньшую сторону до определенного количества знаков после запятой

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

Чтобы округлить до нуля (если число может округляться до 32-разрядного целого числа в диапазоне от -2147483648 до 2147483647), используйте:

rounded=number|0;

Чтобы округлить до нуля (для любого числа), используйте:

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

Округление числа до 0 может быть выполнено путем вычитания его дробной части со знаком число% 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
Math.floor(1+7/8)

Сегодня возился с чужим кодом и обнаружил следующее, которое также выглядит округленным:

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

Для получения дополнительной информации о смещении вправо, распространяющем знаки (> >), см. Побитовые операторы MDN

Мне понадобилось время, чтобы понять, что это делает: D

Но, как было отмечено выше, Math.floor () работает и выглядит более читабельным, на мой взгляд.

Вам нужно поставить -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>
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top