You are viewing limited content. For full access, please sign in.

Question

Question

2 decimal places with javascript function

asked on October 14, 2015 Show version history

After setting up a javascript calculation with 2 fields with decimals, I get a total with a long number after the decimal place.  I am looking to shorten it to 2 numbers after the decimal place.  Upon trying to add .tofixed(2) ended up breaking the calculation.  Any suggestion is appreciated, thanks.

 

 

$(document).ready(function () {
    $('.cf-table-block').on('blur', 'input', sumtotal);
    function sumtotal() {
      	$('.total input').attr('readonly', false);
        var hours = 0;
      	var rate = 0;
      	var Mat = 0;
      	var ODC = 0;
      	var LC = 0;
      	var AO = 0;
      	var SGA = 0;
      	var Profit = 0;	
        var total = 0;
        var subtotal = 0;
      	      
        $('.cf-table-block tbody tr').each(function () {
            hour =  parseNumber($(this).find('.hours input').val()); 
            rate = parseNumber($(this).find('.rate input').val());
          	Mat = parseNumber($(this).find('.Mat input').val());
          	ODC = parseNumber($(this).find('.ODC input').val());
          	LC = parseNumber($(this).find('.LC input').val());
          	AO = parseNumber($(this).find('.AO input').val());
          	SGA = parseNumber($(this).find('.SGA input').val());
          	Profit = parseNumber($(this).find('.Profit input').val());
          	                     
            subtotal = (hour * rate)+Mat+ODC+LC+AO+SGA+Profit;
          	
            $(this).find('.total input').val(subtotal);
            total += subtotal;
        });
        //$('.Grandtotal input').val(total);
    }
    function parseNumber(n) {
        var f = parseFloat(n); //Convert to float number.
        return isNaN(f) ? 0 : f; //treat invalid input as 0;
    }
});

 

0 0

Answer

SELECTED ANSWER
replied on October 14, 2015

Can you show how the calculation fails when you use .toFixed(2)? Using

$(this).find('.total input').val(subtotal.toFixed(2));

works fine for me with your code.

1 0

Replies

replied on October 15, 2015

Hello Tommy,

Which exactly are you using: '.tofixed(2)' or '.toFixed(2)'? JavaScript is case-sensitive, so if you used the all-lowercase option, then the code would be referencing an undefined function.

0 0
replied on October 15, 2015

Thanks guys, I had the .toFixed(2) outside of the subtotal bracket. wink

0 0
You are not allowed to follow up in this post.

Sign in to reply to this post.