0

Please check this code :

function CalCPM()
{
    var nv = document.getElementById('txtviews').value;
    var nc = document.getElementById('txtcost').value;
    var result =parseFloat(nc) / parseFloat(nv)/1000;
    if(!isNaN(result))
    {
        document.getElementById('cpm').value = result.toFixed(4); 
    }
}

it work fine expect when you put comma in the number, means if you put in txtviews 1000000 and in txtcost 3000 you get a correct result that is 3.000

However if you use commas in any of the numbers then the problem starts, like

if you put in txtviews 1,000,000 and in txtcost 3,000

then the result will be 0.000003

OR if you start by putting value for txtcost first then the result will be 3000.0000

which is not a correct value either way, any idea what is the problem??

angelcool.net
  • 2,505
  • 1
  • 24
  • 26
J.Doe
  • 9
  • 1
  • `'100,30,30'.replace(/,/g,'')` – Rayon Apr 25 '16 at 06:17
  • Another simple solution would be to use `type="number"` – Rayon Apr 25 '16 at 06:20
  • Make sure that the the settings for '_decimal symbol_' in your control panel is not `,` instead of `.`. (Control Panel>Region and Language>Format>AdditionalSettings>Numbers>DecimalSymbol). Else ur system is wrongly interpreting the input numbers – Ahs N Apr 25 '16 at 06:34

2 Answers2

0

I believe you'd have to strip them out, and then add them back in (the commas, that is)..

function CalCPM()
{
    var nv = document.getElementById('txtviews').value.replace(',','');
    var nc = document.getElementById('txtcost').value.replace(',','');
    var result =parseFloat(nc) / parseFloat(nv)/1000;
    if(!isNaN(result))
    {
        document.getElementById('cpm').value = Number(result).toLocaleString('en'); 
    }
}
james emanon
  • 11,185
  • 11
  • 56
  • 97
0

This can simply solve by using reg-ex :

 function CalCPM()
  {
    var nv = (document.getElementById('txtviews').value).replace(/,/g,'');
    var nc = (document.getElementById('txtcost').value).replace(/,/g,'');
    var result =parseFloat(nc) / parseFloat(nv)/1000;
    if(!isNaN(result))
    {
    document.getElementById('cpm').value = Number(result).toFixed(4); 
    }
  }