Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Round up to nearest whole number

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()?

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 );    
}
like image 235
ru-pearls Avatar asked Feb 05 '15 18:02

ru-pearls


1 Answers

this can be done by using basic javascript: either use:

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 );    
}
like image 195
Giovanni Le Grand Avatar answered Oct 12 '22 10:10

Giovanni Le Grand