javascript jQuery 向上舍入到最接近的整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28351491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery Round up to nearest whole number
提问by ru-pearls
I am trying to round up the .qty field to the nearest whole number. I am really unsure where to place this in the below code snippet? I take it I should be using Math.ceil()?
我试图将 .qty 字段四舍五入到最接近的整数。我真的不确定将它放在下面的代码片段中的什么位置?我认为我应该使用 Math.ceil()?
function (){
var sm = parseFloat($(this).val());
var tsm = parseFloat($('.tsm', $(this).parent().parent()).val());
var calc = (sm*tsm); // total tiles needed
if($('.addwaste', $(this).parent().parent()).is(':checked')){
var onepercent = calc/100;
var sevenpercent = Math.ceil(onepercent*7);
calc+=sevenpercent;
}
$('.qty', $(this).parent().parent()).val(calc);
$('div.product form.cart .qty').val( calc );
var rawprice = parseFloat($('.rawprice', $(this).parent().parent()).val());
var total = (rawprice*calc).toFixed(2);
$('.total', $(this).parent().parent()).html(total);
$('div.product .price .amount').html( '£' + total );
}
回答by Giovanni Le Grand
this can be done by using basic javascript: either use:
这可以通过使用基本的 javascript 来完成:要么使用:
Math.floor(number here); <- this rounds it DOWN so 4.6 becomes 4
Math.round(number here); <- this rounds it UP so 4.6 becomes 5
its either floor and round OR Floor and Round.
它要么是地板和圆形,要么是地板和圆形。
so with your code it would be:
所以你的代码将是:
function (){
var sm = parseFloat($(this).val());
var tsm = parseFloat($('.tsm', $(this).parent().parent()).val());
var calc = (sm*tsm); // total tiles needed
if($('.addwaste', $(this).parent().parent()).is(':checked')){
var onepercent = calc/100;
var sevenpercent = Math.ceil(onepercent*7);
calc+=sevenpercent;
}
calc = Math.round(calc);
$('.qty', $(this).parent().parent()).val(calc);
$('div.product form.cart .qty').val( calc );
var rawprice = parseFloat($('.rawprice', $(this).parent().parent()).val());
var total = (rawprice*calc).toFixed(2);
$('.total', $(this).parent().parent()).html(total);
$('div.product .price .amount').html( '£' + total );
}