Adding floats together with commas and decimal places

Someone contacted me about adding some numbers together with comma’s and dots within there values, here is the email via the contact me page.

“Please I need a javascript code that can enable me add two or more numbers containing dot(.) and/or comma (,) together. For example, 122.34 + 233.56. Or/And 233,239.34 + 323,322.44. Thanks in advance.”

Here is the code that will accomplish the request.

<html>
<script type="text/javascript" >
       function load()
       {
               var value1="233,122.34";
               var value2="233.56";
               alert(parseFloat(value1.replace(",",""))+parseFloat(value2.replace(",","")));
       }
 
</script>
<body onload="load()">
</body>
</html>

The main part is the parseFloat and replacing the “,” with nothing “” to remove the none float characters via the object replace method.

Leave a Reply

Your email address will not be published. Required fields are marked *