CodeBlanks Logo Icon CodeBlanks

Number input and operator selection

JavaScript course · Beginner · Lesson 26/133

Take two numbers and an operator from the user to set up the operation.

Number input: from string to number

The values the user enters always arrive as strings. To do math on them we must first convert them to numbers. We use the parseFloat function for this.

parseFloat("25") gives us the number 25. parseFloat("3.14") gives 3.14. A value that cannot be converted returns NaN.

We store the first value as a string in const firstInput, then convert it with const first = parseFloat(firstInput). This way we keep both the original text and the number.

Operation selection: operator input

The calculator must know which operation to perform. We store the operation as a string: "+", "-", "*" or "/".

We take the second number the same way, as a string: const secondInput = "4". Then we convert it with parseFloat.

The result is not known yet, so we declare it with let result. let is for variables whose value will change later; const is for values that never change.

Exercise Second number, operation and parsing

In the previous lesson you declared firstInput. Now add these: put "+" in const operator, and "4" in const secondInput. Then convert firstInput to const first and secondInput to const second with parseFloat. Finally declare an unassigned result variable with let result and print the three values with console.log.

Show example solution
// The user's first value
const firstInput = "25";
const operator = "+";
const secondInput = "4";
const first = parseFloat(firstInput);
const second = parseFloat(secondInput);
let result;
console.log(first, operator, second);

Test yourself

  1. What is the result of parseFloat("42.5")?

    parseFloat("42.5")
    • "42.5" (stays a string)
    • 42 (rounded to integer)
    • 42.5 (returns a decimal)
    • NaN
    Show answer

    42.5 (returns a decimal) — Correct. parseFloat keeps the decimal part and returns the number 42.5.

  2. Complete the second number variable

    const firstInput = "25";
    const operator = "+";
    ____
    const first = parseFloat(firstInput);
    Show answer
    const firstInput = "25";
    const operator = "+";
    const secondInput = "4";
    const first = parseFloat(firstInput);
  3. Match variables to their roles

    firstInput
    First number (string)
    operator
    Selected operation (+, -, *, /)
    secondInput
    Second number (string)
    first
    Parsed first value

All lessons in Beginner