2

just wondering if I could get some help. Driving myself crazy over something which I'm sure is easy peasy! :(

Basically I'm trying to get a calculator that will calculate two variables. I've kind of got this working by hook or by crook....

But the numbers I put in will be copy and pasted from somewhere else, and thus will more than likely have a comma in it to separate eg one thousand will be 1,000.00 (possible whitespace after value).

This breaks my calculator giving a result of "nAn" and I can't seem to find a work around. Would anyone be able to assist?

Thanks very much.

My code thus far:

<HTML>
<HEAD>
  <TITLE>calc</TITLE>

  <SCRIPT language="javascript" type="text/javascript">
    function division() {
      a=Number(document.calculator.number1.value);
      b=Number(document.calculator.number2.value);
      c=(a/b)*10000;

      document.calculator.total.value=c;
    }
  </SCRIPT>
</HEAD>
<BODY>
  <FORM name="calculator">
    First input: <INPUT type="text" name="number1"> <br>
    Second input: <INPUT type="text" name="number2"> <br>
    <INPUT type="button" value="Calculate" onclick="javascript:division();">
    Total: <INPUT type="text" name="total"> <br>
  </FORM>
</BODY>
</HTML>
Dario
  • 618
  • 1
  • 11
  • 28
  • I would say that if you get `NaN` (Not A Number), you should tell the user to care about what he's typing rather than trying to get a number at any price. –  Nov 02 '17 at 12:10
  • Imagine it's a bank transfer and you guess the wrong number :-P –  Nov 02 '17 at 12:58

3 Answers3

3

Here's a little helper function you can use to parse the inputs. It will remove commas and return a number.

function parseInput(input) {
  return Number(input.replace(/,/g, ''));
}
Niklas Higi
  • 2,188
  • 1
  • 14
  • 30
0

function division()

{

a=document.calculator.number1.value;
b=document.calculator.number2.value;

a = parseFloat(a.replace(',',''));
b = parseFloat(b.replace(',',''));

c=(a/b)*10000;

document.calculator.total.value=c;
}
0

here is your example:

<!DOCTYPE html>
<html>

<head>
    <title></title>
</head>
<script type="text/javascript">
function division() {
    var a = document.calculator.number1.value;
    var number1 = a.replace(/,/g, '');
    var b = document.calculator.number2.value;
    var number2 = b.replace(/,/g, '');
    var c = (Number(number1) / Number(number2)) * 10000;
    document.calculator.total.value = c;
}
</script>

<body>
    <FORM name="calculator">
        First input:
        <INPUT type="text" name="number1">
        <br> Second input:
        <INPUT type="text" name="number2">
        <br>
        <INPUT type="button" value="Calculate" onclick="javascript:division();"> Total:
        <INPUT type="text" name="total">
        <br>
    </FORM>
</body>

</html>
Sahil Jariwala
  • 243
  • 2
  • 5
  • 19