gpt4 book ai didi

javascript - 如何将值四舍五入到小数点后 1 位?

转载 作者:行者123 更新时间:2023-12-01 08:32:10 25 4
gpt4 key购买 nike

我在不同的字段集中有一组单选按钮。我能够获取单选按钮的值并除以该数字,但我不确定如何对其进行舍入。

我想将总分的值四舍五入到小数点后一位。

HTML

<fieldset>
<input class="calc" type="radio" id="star15" name="rating2" value="5" /><label for="star15">5 stars</label>
<input class="calc" type="radio" id="star14" name="rating2" value="4" /><label for="star14" class="m-r-48">4 stars</label>
<input class="calc" type="radio" id="star13" name="rating2" value="3" /><label for="star13" class="m-r-48">3 stars</label>
<input class="calc" type="radio" id="star12" name="rating2" value="2" /><label for="star12" class="m-r-48">2 stars</label>
<input class="calc" type="radio" id="star11" name="rating2" value="1" /><label for="star11" class="m-r-48">1 star</label>
</fieldset>

<fieldset>
<input class="calc" type="radio" id="star20" name="rating3" value="5" /><label for="star20">5 stars</label>
<input class="calc" type="radio" id="star19" name="rating3" value="4" /><label for="star19" class="m-r-48">4 stars</label>
<input class="calc" type="radio" id="star18" name="rating3" value="3" /><label for="star18" class="m-r-48">3 stars</label>
<input class="calc" type="radio" id="star17" name="rating3" value="2" /><label for="star17" class="m-r-48">2 stars</label>
<input class="calc" type="radio" id="star16" name="rating3" value="1" /><label for="star16" class="m-r-48">1 star</label>
</fieldset>

<fieldset>
<input class="calc" type="radio" id="star25" name="rating4" value="5" /><label for="star25">5 stars</label>
<input class="calc" type="radio" id="star24" name="rating4" value="4" /><label for="star24" class="m-r-48">4 stars</label>
<input class="calc" type="radio" id="star23" name="rating4" value="3" /><label for="star23" class="m-r-48">3 stars</label>
<input class="calc" type="radio" id="star22" name="rating4" value="2" /><label for="star22" class="m-r-48">2 stars</label>
<input class="calc" type="radio" id="star21" name="rating4" value="1" /><label for="star21" class="m-r-48">1 star</label>
</fieldset>

Total Score:
<input type="text" name="sum" />

JS

function calcscore(){
var score = 0;
$(".calc:checked").each(function(){
score+=parseInt($(this).val(),10);
});
$("input[name=sum]").val(score / 8)
}
$().ready(function(){
$(".calc").change(function(){
calcscore()
});
});

这是一个 fiddle :https://jsfiddle.net/b4y7adg3/1/

最佳答案

您可以将值乘以 10 舍入,然后除以 10:

var value = Math.round(number / 8 * 10) / 10;

参见your fiddle

您也可以使用.toFixed(1);但是,这将强制使用小数,例如 6 的值将变为 6.0

关于javascript - 如何将值四舍五入到小数点后 1 位?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60175289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com