0

How do i take user input and convert the string into an integer that i can use mathematically in a function??

Totally new to coding and trying to build a simple calculator. I am not sure what i am doing wrong, any help would be appreciated.

    function TLV() 
    {
            var TLVday = Integer.valueOf("getTLVdate");
        var OBday = Integer.valueOf("getOBdate");
        if (TLVday<OBday)
        {
            DD = OBday + 10;
        }
        else
        {
            DD = OBday + 30;
        }
        document.getElementById("TLVoutput").innerHTML=DD;
    }


<form name="myform" id="frm1">
    <table style="border:0;">
    <tr>
    <td>OB Start Day:</td>
    <td><input type="text" id="getOBdate"/></td>
    </tr>
    <tr>
    <td>TLV Start Day: </td>
    <td><input type="text" id="getTLVdate"/></td>
    <td id="TLVoutput"></td>
    </tr>
<button onclick="TLV()">Calculate</button>
    </table>
</form>
3
  • The code in "TLV" is part Java, part JavaScript. Commented Jul 19, 2013 at 21:56
  • you use parseFloat(num); Commented Jul 19, 2013 at 21:56
  • Can you please repaste your code WITHOUT copying it by hand? you have issues and typos. For exmaple, function TLV is missing a } and has a stray " around Commented Jul 19, 2013 at 21:56

4 Answers 4

3

Here are three common ways:

var myNumber = +myString;            // coerce string to number
var myFloat = parseFloat(myString);  // parse as floating point number
var myInt = parseInt(myString, 10);  // parse as a base-10 integer

Documentation:

+ operator - mdn msdn
parseFloat() method - mdn msdn
parseInt() method - mdn msdn

Each of these techniques have their own quirks. Because of the dynamic nature of JavaScript, type conversion is not simple.

parseInt()

parseInt() produces either an integer or a NaN by reading the digits from left to right. If your string contains only numeric digits, and you are using a browser that supports ECMAScript 5 (IE8 and older do not), It is very straightforward - you get those digits as a number in base 10. In IE8 or older, if the first digit is 0, you'll get the number in octal. Eg, parseInt("010") returns 10 in modern browsers and 8 in older browsers. To correct for this, always specify the radix in the second parameter. parseInt("010", 10) always returns 10, regardless of browser version.

Parsing stops at the first non-digit character. So, parseInt("4 donuts") returns 4 as does parseInt("4,000"). If the first character in the string is not a digit or + or -, you will get NaN, so you can't parse "$5".

If the string starts with 0x it is treated as Hexadecimal (base 16). parseInt("0x10") returns 16. Same thing if you explicitly specify base 16 with the radix: parseInt("10", 16).

parseFloat()

parseFloat() is similar to parseInt(). The differences are that parseFloat() only works with base 10, and, obviously, it produces a floating point number.

Addition operator (+)

In JavaScript, a string can be used as a number. When a JavaScript construct accepts a number and gets something else (such as a string), it very typically tries to "coerce" it to a number. One case where we see this behavior is the + operator. In some ways, coercion is more strict than parsing -- The entire string must be numeric, not just the beginning, or else it returns NaN. But, in another way, it's less strict -- an empty or whitespace string returns 0 when coerced to a number, but returns NaN when parsed.

Besides the addition operator, other ways to coerce a string to a number include:

  • Use the Number() constructor as a function
  • Pass a string to a method that accepts a number, eg Math.floor("10")
  • Use a string with an arithmetic operator:
var string = "10";
var num = string * 1;
var num = string / 1;

Get the full details about how a string is coerced to a number in the ECMAScript Spec, Section 9.3.1.

Sign up to request clarification or add additional context in comments.

4 Comments

Don't forget to specify radix for parseInt please
@Shawn31313 - I'm sure we can come up with more than 4 ways
Ha, thats the only other way I can think of.
@Shawn31313 - How about myString *= 1 or - -myString. Some more examples added to my answer at the end.
1

There is no such thing as 'Integer', that's Java not JavaScript.

To parse a string into an integer, you can use parseInt, but if you don't care whether it's an integer or floating-point there's no need to do anything - it will automatically convert when you try to use it.

However, you cannot access a field value just by using its id. Instead you must use the DOM - 'document.getElementById("getTVLdate").value'

Comments

1

Use parseInt('value', 10 ) to convert a string to a number

To read the value use this syntax .. Where it selects the element based on the id and then use the value property on it to get the value.

Remember this is JavaScript and not Java

var TLVday = document.getElementById.('getTLVdate').value

Change your code to

var button = document.getElementById('calculate');

button.addEventListener('click', TLV);

function TLV() {
    var TLVday = parseInt(document.getElementById('getTLVdate').value, 10),
        OBday = parseInt(document.getElementById('getOBdate').value, 10),
        DD = 0;
    if (TLVday < OBday) {
        DD = OBday + 10;
    } else {
        DD = OBday + 30;
    }
    document.getElementById("TLVoutput").innerHTML = DD;
}

Also avoid binding events inline. Always a better idea to separate your concerns.

Check Fiddle

6 Comments

errr you may want to fix your syntax :P
DD = 0 should have a semicolon ... it's better to avoid the , operator in var declarations for clarity and re-pastability of code.
"JavaScript" and "Java", especially not "JAVA".
I can see how he confused it. The OP probably thought JavaScript was a browser implementation of Java :P ha
Worked like a charm thank you for your help and patience with such a rookie question.
|
0

If you have a string you need converted to a number you can use parseInt , parseFloat if you need a floating point.

parseInt('84945');

You can give another parameter parseInt('84945',10); to specify the base, bas 10 in this case

7 Comments

Don't forget to specify radix for parseInt please
Another note, but in these cases is better to specify it completely: you are allowed, but you HAVE to specify a radix for parseInt, otherwise the compiler will do that for you... With unexpected results, I'd say.
@LightStyle I understand what your saying, many times I will post my answer way too fast because I have to compete with these people for rep, at this point the answer is a lost cause
If you're here just for reputation then I think you can give up, seriously. SO is not intended to be the site which has a winner who is the one with the most reputation. SO **should be**(because it is not, anymore I'd say) a Q&A site which enhances the completeness of the answer and not "how fast you can digit". It's about quality IMHO.
@LightStyle well I mostly use it to try and stay sharp, one problem is definitely that first answer almost always wins especially on questions like this, I would like to answer more interesting questions but unfortunately most people do not ask very good questions
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.