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

Question

Question

Sum in Form to show only two decimal places

asked on January 31, 2014

Running a basic script from Forms that shows a sum.  I would like the sum to produce a result for example $1.98 instead of $1.987655. What should be added or changed?

 

$(document).ready(function () {
  $('.cf-table-block').on('blur', 'input', sumtotal);
 
  function sumtotal() {
      var sum = 0;
      $('.cf-table-block tbody tr').each(function () {
          var s = 0;
          s = parseNumber($(this).find('.price input').val()) * parseNumber($(this).find('.quantity input').val());
          $(this).find('.subtotal input').val(s);
          sum += s;
      });
      $('.total input').val(sum);
  }
  function parseNumber(n) {
      var f = parseFloat(n); //Convert to float number.
      return isNaN(f) ? 0 : f; //treat invalid input as 0;
  }
});

 

2 0

Answer

APPROVED ANSWER
replied on January 31, 2014

Try this:

 

$(document).ready(function () {
  $('.cf-table-block').on('blur', 'input', sumtotal);
 
  function sumtotal() {
      var sum = 0;
      $('.cf-table-block tbody tr').each(function () {
          var s = 0;
          s = parseNumber($(this).find('.price input').val()) * parseNumber($(this).find('.quantity input').val());
          $(this).find('.subtotal input').val((s).toFixed(2));
          sum += s;
      });
      $('.total input').val((sum).toFixed(2));
  }
  function parseNumber(n) {
      var f = parseFloat(n); //Convert to float number.
      return isNaN(f) ? 0 : f; //treat invalid input as 0;
  }
});

We're using the .toFixed() method to limit the number of decimal places to two.

2 0
replied on January 31, 2014

Thank you!

0 0
replied on January 31, 2014

You're welcome!

0 0

Replies

replied on January 31, 2014

This worked perfectly!!

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

Sign in to reply to this post.