skip to Main Content

I’ve got everything else working in this contact form invoice but I am not able to make this script to return total money value in the following format: 00.00

I have added the .tofixed(2) in several places and have only managed to make it return .00 when it should be .60.

I am a self-learner so I am struggling to figure it out.

<script type="text/javascript">
function findTotal(){
    var arr = document.getElementsByName('qty');
    var tot=0;
    for(var i=0;i<arr.length;i++){
        if(parseInt(arr[i].value))
            tot += parseInt(arr[i].value);
    }
    document.getElementById('total').value = tot;
}

    </script>

3

Answers


  1. There’s 2 method in JavaScript that deals with parsing of number from string:

    When dealing with numbers that has decimal points, you would need to use parseFloat instead so the decimal part isn’t discarded.

    How parseInt() works is, it will try to match as many valid characters as possible (following the radix passed in the second argument, usually default to 10 except special case*):

    parseInt('123.45'); // 123
    parseInt('12abc'); // 12
    

    This is why we need parseFloat() to solve the first scenario:

    parseFloat('123.45'); // 123.45
    parseFloat('12abc'); // 12
    

    (Unlike parseInt(), it doesn’t accept a radix second argument and can only be base of 10)


    Solution based on your case:

    function findTotal() {
      var arr = document.getElementsByName('qty');
      var tot = 0;
      for (var i = 0; i < arr.length; i++) {
        if (parseFloat(arr[i].value)) tot += parseFloat(arr[i].value);
      }
      document.getElementById('total').value = tot.toFixed(2);
    }
    
    Login or Signup to reply.
  2. As an option, you can us totalValue.toLocaleString() function which will format your target string according to the required currency format.

    <p>Total: <span id="total"></span></p>
    
    <script>
      const totalValue= 1234.56; // You can add your logic of incrementing total value here
      const formatTotal = totalValue.toLocaleString('en-US', {
        style: 'currency',
        currency: 'EUR'
      });
      document.getElementById('total').textContent = formatTotal;
    </script>
    
    Login or Signup to reply.
  3. In javascript, the number is not converted to float until it doesn’t have a decimal value greater than 0 even if we use pasrseFloat() on that.

    For a decimal number, parseInt() returns us a whole number and on the other hand, parseFloat() provides the results with the decimal value.

    For example,

    let a = 5;
    console.log(parseFloat(a)); //returns 5 even when we have parsed it to float.
    console.log(parseFloat(a)); //returns 5, a whole number.
    
    let b = 5.0;
    console.log(parseFloat(b)); //still returns 5 even though we have 0 as a decimal point.
    
    let c = 5.1;
    console.log(parseFloat(c)); //now returns 5.1 as we have a decimal point greater than zero.
    
    console.log(parseInt(c)); //returns 5, and converts the decimal number to the whole number.

    This is where a formatter comes into play i.e. toFixed() which formats the number up to decimal points entered and returns it as a string.

    The solution for your code is to change the parseInt to parseFloat while calculating and formatting it with toFixed wherever you need to display it.

    function findTotal(){
    var arr = document.getElementsByName('qty');
    var tot=0;
    for(var i=0;i<arr.length;i++){
        if(parseFloat(arr[i].value))
            tot += parseFloat(arr[i].value);
    }
    document.getElementById('total').value = tot.toFixed(2);
    

    }

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search