How to allow comma to my addition codes
-
27-10-2019 - |
Question
These code are working; adding correctly. The problem is that if I want to add 99000000.00 + 199000000.00 it displays 298000000.00.
How can I make it 99,000,000.00 + 199,000,000.00 that displays 298,000,000.00?
Every time I compute numbers with comma, it results to NAN/Invalid. But if I compute numbers without comma, it computes well. How to allow comma in text area/numbers inputted by the users without having a NAN/Invalid result?
Please see code used below:
HTML CODE:
<table width="460" border="1">
<tr>
<tr>
<td>SOUTH CLUSTER (391)</td>
<td><input name="scc" type="text" size="25" id="scc" value="0.00"/></div></td>
</tr>
<tr>
<td>CENTRAL CLUSTER(387)</td>
<td><input name="ccc" type="text" size="25" id="ccc" value="0.00" /></div></td>
</tr>
<tr>
<td>NORTH CLUSTER(393)</td>
<td><input name="ncc" type="text" size="25" id="ncc" value="0.00" /></div></td>
</tr>
<tr>
<td >C HUB(390)</td>
<td><input name="vch" type="text" size="25" id="vch" value="0.00"/></div></td>
</tr>
<tr>
<td>CH HUB(397)</td>
<td><input name="mch" type="text" size="25" id="mch" value="0.00"/></div></td>
</tr>
<tr>
<td>NLC HUB(399)</td>
<td><input name="nlch" type="text" size="25" id="nlch" value="0.00"/></div></td>
</tr>
<tr>
<td>SLC HUB(396)</td>
<td><input name="slch" type="text" size="25" id="slch" value="0.00"/></div></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td>
<td><div class="style66" align="center"><input type="button" value="ADD" onclick="civ()"></center></td>
</tr>
JAVASCRIPT CODES:
function civ(){
civ1=Number(document.addition.scc.value);
civ2=Number(document.addition.ccc.value);
civ3=Number(document.addition.ncc.value);
civ4=Number(document.addition.vch.value);
civ5=Number(document.addition.mch.value);
civ6=Number(document.addition.nlch.value);
civ7=Number(document.addition.slch.value);
valNum1=Math.floor((civ1+civ2+civ3+civ4+civ5+civ6+civ7)*100)/100;
document.addition.civ123.value=valNum1;
}
Solution
When you have commas, it is Not a Number (NaN).
A quickfix would be to add in a function to convert them to a number
function NumWithComma(num){
return parseInt(num.replace(",",""));
}
then do
civ1 = NumWithComma(document.addition.scc.value);
This is a quickfix, in my opinion there are many things wrong with what you have posted...hopefully this helps somehow
OTHER TIPS
Use replace to clean the commas:
number_with_commas.replace(/,/g, '');
Or to clean everything that is not a digit or a decimal point:
number_with_random_noise.replace(/[^0-9.]/g, '');
Use a regular expression replace to remove any commas, and parseInt() to change the resulting string into a number.
parseInt(yourVariable.replace(/\,/g,''),10)
Note that the result might still fail because obviously your users can type any old nonsense into the field. Read the doco on parseInt().