猿问

如何在 0.5 以外的其他阈值处舍入数字

我将如何更改此代码,以便可以将数字 7 替换为 7 到 16 之间的任何数字?


    var lvalue = $( ".leave-input" ).val();

    if (lvalue <=  7.29) {

      lvalue = roundDown();

    } else if (lvalue >= 7.3) {

      lvalue = roundUp();

    }

我正在尝试将用户输入的时间舍入最近的时间。我在使用时间时遇到了麻烦,所以现在只使用他们输入的数字。


为了澄清而不是为每个数字 7、8、9 等都有一个 if 语句。有没有办法重写当前代码,以便“7”可以是 7 到 16 之间的任何数字?


Qyouu
浏览 133回答 4
4回答

芜湖不芜

如果添加0.2到该值,则可以使用Math.round():input.oninput = function() {&nbsp; let lvalue = +document.getElementById('input').value + 0.2;&nbsp; document.getElementById('output').innerHTML = Math.round(lvalue);}<input id="input" type="text"><div id="output"></div>

慕姐8265434

您可以使数字小于 1,那么它应该适用于所有情况:let lvalue = $(".leave-input").val();const baseValue = Math.round((lvalue - Math.floor(lvalue)) * 100) / 100;if (baseValue<= 0.29) {&nbsp; &nbsp; lvalue = roundDown();} else if (baseValue>= 0.3) {&nbsp; &nbsp; lvalue = roundUp();}这是一个工作示例:function calculate() {&nbsp; let lvalue = Number(document.getElementById('input').value)&nbsp; const baseValue = Math.round((lvalue - Math.floor(lvalue)) * 100) / 100;&nbsp; if (baseValue <= 0.29) {&nbsp; &nbsp; lvalue = Math.floor(lvalue);&nbsp; } else if (baseValue >= 0.3) {&nbsp; &nbsp; lvalue = Math.ceil(lvalue);&nbsp; }&nbsp; document.getElementById('output').innerHTML = lvalue;}<input id="input" type="text" /><button onClick="calculate()">Round</button><div id="output"></div>

子衿沉夜

$(".leave-input").change(function(){&nbsp; let lvalue = parseFloat($(".leave-input").val());&nbsp; const val = lvalue * 100 % 100 ;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; if (val <= 29) {&nbsp; &nbsp; &nbsp; lvalue = Math.floor(lvalue);//roundDown();&nbsp; } else {//your condition will skip anything between .29 and .30&nbsp; &nbsp; &nbsp; lvalue = Math.ceil(lvalue);//roundUp();&nbsp; }&nbsp; $(".result").html(lvalue);})<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><input class="leave-input" /><div class="result"></div>

慕田峪4524236

let lvalue = $(".leave-input").val();const integer = Math.trunc(lvalue);const decimal = lvalue % 1;// or you could do lvalue - intergerif (integer >= 7 && integer <= 16) {&nbsp; &nbsp; if (decimal <= 0.29) {&nbsp; &nbsp; &nbsp; &nbsp; lvalue = roundDown();&nbsp; &nbsp; } else if (decimal >= 0.3) {&nbsp; &nbsp; &nbsp; &nbsp; lvalue = roundUp();&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答