0

I have read through a few examples if how to get my decimal point values down to 2 places but nothing I have tried seems to work with my current function I use to calculate subtotals .. Can anyone give me some advice on how to make this work correctly. (for example: I currently get values back like 1848.0198768 but need it to be just be 1848.02).

Here is my calculateSubTotal code:

  function calculateSubtotal()
  {
   var sum = 0;
   $(".clamount").each(function(i,e)
   {
    var v = parseFloat($(e).val());
     if(isNaN(v))
     {
      v = 0;
     }
    if($(e).attr("data-column")=="pbDebit") v = -v;
    sum += v;
   });
  $("#subtotal").text(sum);
  $("#bTotalBookingAmount").val(sum);

 I have tried the following to no avail:
 // var subtotalNew = parseFloat($('#subtotal').text(sum).toFixed(2));
 // $("#subtotal").text(subtotalNew);
 // $("#bTotalBookingAmount").val(subtotalNew);
 }

Any guidance would be greatly appreciated. I am assuming the code isnt working due to a NaN value (which I attempted to account for in the if(isNaN(v)) section, which it is always numbers and never any letter characters so I am a little confused.

bones
  • 81
  • 10
  • 1
    See [`number.toFixed(2)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed). Btw, the PHP tag should be a Javascript tag. – Kenney Apr 11 '16 at 18:16
  • Thank you I adjusted flag and will look into the number.toFixed(2) ... Many thanks – bones Apr 11 '16 at 18:17

2 Answers2

1

Use toFixed(2) to cut down value and round it to 2 decimal values.

Arjun J Gowda
  • 720
  • 10
  • 21
  • Thanks Arjun, adjusting the code to the following (per Kenny's recc) addressed the issue: – bones Apr 11 '16 at 18:34
0

Thank you Kenney ... After reading through your suggested link I have the code working properly now. I dont think I am able to flag you as the correct answer due to it only being a comment. But that information worked out perfectly. Thank you very much.

 function calculateSubtotal()
 {
  var sum = 0;
  $(".clamount").each(function(i,e)
  {
   var v = parseFloat($(e).val());
   if(isNaN(v))
   {
    v = 0;
   }
  if($(e).attr("data-column")=="pbDebit") v = -v;
  sum += v;
});
  sum = sum.toFixed(2);
bones
  • 81
  • 10