omega1
omega1

Reputation: 1052

Issue with decimal points and formatting with javascript and HTML forms

I'm not familiar with javascript, apologies if this is a simple task.

I am trying to update a total with options selected via a HTML form using checkboxes but I'm having issues with the formatting of the numbers. I have this working, but I'm having issues with the formatting. The current behaviour is that no decimal points are displayed, but functionality is correct. If I change parseInt to parseFloat, I get the decimal points, but it adds many decimal points if I check and uncheck items. If I add two items, that would give me a figure of 5.90 it only displays 5.9 instead of 5.90.

The desired behaviour would be to only have 2 decimal points (I'm not sure why it even displays things like 2.95000001) and when the amount is 5.90 it displays correctly instead of 5.9

Here is my code so far

<head>
<script type="text/javascript">
    var total = 0;
    function test(item){
        if(item.checked){
           total+= parseInt(item.value);
        }else{
           total-= parseInt(item.value);
        }
        //alert(total);
        document.getElementById('Totalcost').innerHTML = total;
    }
</script>
</head>
<body>
<label>
<input type="checkbox" value="2.95" onClick="test(this);"  />Product 1</label>
<label>
<input type="checkbox" value="2.95" onClick="test(this);"  />Product 2</label>
<h3>Total Amount : $<span id="Totalcost"> </span></h3>

Thank you.

EDIT : I also tried changing this line:

total-= parseInt(item.value);

to this

total-= parseInt(item.value).toFixed(2);

But it just adds the amounts to the end of the total instead of adding them up (like this output : Total Amount : £02.002.002.00

Upvotes: 2

Views: 680

Answers (2)

user8108377
user8108377

Reputation:

if you are looking to have only 2 decimal number after the "." you can try this code

 var total = 0;
        function test(item){
            if(item.checked){
               total+= parseFloat(item.value)
            }else{
               total-= ParseFloat(item.value)
            }
            //alert(total);
            document.getElem

entById('Totalcost').innerHTML = total.toFixed(2);
    }

Upvotes: 1

user1405631
user1405631

Reputation:

toFixed(2) i think is what you need

https://www.w3schools.com/jsref/jsref_tofixed.asp

<head>
<script type="text/javascript">
    var total = 0;
    function test(item){
        if(item.checked){
           total+= parseFloat(item.value);
        }else{
           total-= parseFloat(item.value);
        }
        //alert(total);
        document.getElementById('Totalcost').innerHTML = total.toFixed(2);
    }
</script>
</head>
<body>
<label>
<input type="checkbox" value="2.95" onClick="test(this);"  />Product 1</label>
<label>
<input type="checkbox" value="2.95" onClick="test(this);"  />Product 2</label>
<h3>Total Amount : $<span id="Totalcost"> </span></h3>

Upvotes: 3

Related Questions