Back

Activity 1.7 Numeric Input

divider

Introduction

Activity 1.7

Numeric Input

Topics

  • Issues with strings and arithmetic
  • Converting strings into numbers
    • The parseInt() function
    • The parseFloat() function
  • Converting user input into numeric form

Issues with Strings and Arithmetic

To convert strings to numbers for computation, you can't rely on the numbers in strings to perform math correctly.

"3" + "3" // 33

2 * "3" + "3" // 63

Issues with Strings and Arithmetic

JavaScript might let you get away with doing math with strings, but many languages won't.

Javascript: 3 * "3" -> 9

Python: "3" * 3 -> "333"

Java: "3" * 3 -> Syntax Error

Converting Strings into Numbers

JavaScript has two functions for converting strings into numbers:

parseInt()

parseFloat()

The parseInt() Function

The parseInt() function attempts to take a string and convert it into an integer number.

parseInt("55") -> 55

parseInt("29.25") -> 29

parseInt("35 years") -> 35

parseInt("Mortimer is 35") -> NaN (Not a Number)

The parseFloat() Function

The parseFloat() function attempts to take a string and convert it into a floating-point number (decimal).

parseFloat("29.25") -> 29.25

parseFloat("55") -> 55

parseFloat("35.95 cents") -> 35.95

parseFloat("Amount: $35.95") -> NaN (Not a Number)

Converting User Input into Numeric Form

Get Input and Convert: 2 Steps
  1. Get the user's input as a string: The prompt() function gets whatever the user types and saves it as a string.
  2. Convert the string to a number: Use parseFloat() to turn the text string into a usable number so you can do math with it.
let input = prompt("Enter your dollar amount:"); // Step 1
let dollars = parseFloat(input); // Step 2
console.log(dollars + 10); // Now you can do math!

Converting User Input into Numeric Form

Get Input and Convert: 1 Step

Combine getting the user's input and convert it into a number by nesting the prompt() function inside the parseFloat() function. JavaScript evaluates what's inside the parentheses first.

let dollars = parseFloat(prompt("Enter your dollar amount:"));
console.log(dollars + 10);

Converting User Input into Numeric Form

Get Input and Convert: 1 Step

Combine getting the user's input and convert it into a number by nesting the prompt() function inside the parseFloat() function. JavaScript evaluates what's inside the parentheses first.

let dollars = parseFloat(prompt("Enter your dollar amount:"));
console.log(dollars + 10);

Converting User Input into Numeric Form

Get Input and Convert: 1 Step

Combine getting the user's input and convert it into a number by nesting the prompt() function inside the parseFloat() function. JavaScript evaluates what's inside the parentheses first.

let dollars = parseFloat(prompt("Enter your dollar amount:"));
console.log(dollars + 10);

parseInt() vs. parseFloat()

Use parseInt() when you need a whole number (student ID, age, number of people, etc.).

Use parseFloat() when you need a decimal number (dollar amount, weight, GPA, etc.).

Key Terms

Numeric Input
The process of getting numerical data from a user, typically via a keyboard, for a program to use in calculations.
Nesting Functions
The practice of placing one function call inside another.

'F' → Fullscreen

Objectives

  • icon Prompting a user for input and saving it to a variable
  • icon Converting input from a string to a number
    • icon Convert a string into an integer using parseInt()
    • icon Convert a string into a floating-point number (decimal) using parseFloat()
divider

Activity Tasks

  • icon Create a new project named 1-7-numeric-input.js.
  • icon Complete each task individually.

Task 1: Age to Months Calculator

  • icon Convert the user's input to a number over two lines.
1-7-numeric-input.js
console.log("--- Demo 1 - Age to Months Calculator ---");
// Convert input to a number in two steps (simple, but tedious).
let input = prompt("Enter your age:"); // 1) User types in age
let age = parseInt(input); // 2) Convert string input to an integer
console.log(`You are ${age} years old. That's ${age * 12} months old!`);
alert("\nPress enter to continue...");
//

Task 2: Square Area Calculator

  • icon Convert the user's input to a number in one line.
1-7-numeric-input.js
console.log("--- Demo 1 - Age to Months Calculator ---");
// Convert input to a number in two steps (simple, but tedious).
let input = prompt("Enter your age:"); // 1) User types in age
let age = parseInt(input); // 2) Convert string input to an integer
console.log(`You are ${age} years old. That's ${age * 12} months old!`);
alert("\nPress enter to continue...");
// -----------------------------------------------------------------------------
console.log("--- Demo 2 - Square Area Calculator ---");
// Convert input to a number in one step
let length = parseFloat(prompt("Enter the length of the square: "));
let area = length * length;
console.log(`The area of the square is ${area}`);
alert("\nPress enter to continue...");
//

Task 3: Score Calculator

1-7-numeric-input.js
console.log("--- Demo 1 - Age to Months Calculator ---");
// Convert input to a number in two steps (simple, but tedious).
let input = prompt("Enter your age:"); // 1) User types in age
let age = parseInt(input); // 2) Convert string input to an integer
console.log(`You are ${age} years old. That's ${age * 12} months old!`);
alert("\nPress enter to continue...");
// -----------------------------------------------------------------------------
console.log("--- Demo 2 - Square Area Calculator ---");
// Convert input to a number in one step
let length = parseFloat(prompt("Enter the length of the square: "));
let area = length * length;
console.log(`The area of the square is ${area}`);
alert("\nPress enter to continue...");
// -----------------------------------------------------------------------------
console.log("--- Demo 3 - Score Calculator ---");
let score1 = parseFloat(prompt("Enter the score for game 1: "));
let score2 = parseFloat(prompt("Enter the score for game 2: "));
let score3 = parseFloat(prompt("Enter the score for game 3: "));
let totalScore = score1 + score2 + score3;
console.log(`Your total score for the three games is ${totalScore}!`);
alert("\nPress enter to continue...");
//

Task 4: Shopping Cart Subtotal

1-7-numeric-input.js
console.log("--- Demo 1 - Age to Months Calculator ---");
// Convert input to a number in two steps (simple, but tedious).
let input = prompt("Enter your age:"); // 1) User types in age
let age = parseInt(input); // 2) Convert string input to an integer
console.log(`You are ${age} years old. That's ${age * 12} months old!`);
alert("\nPress enter to continue...");
// -----------------------------------------------------------------------------
console.log("--- Demo 2 - Square Area Calculator ---");
// Convert input to a number in one step
let length = parseFloat(prompt("Enter the length of the square: "));
let area = length * length;
console.log(`The area of the square is ${area}`);
alert("\nPress enter to continue...");
// -----------------------------------------------------------------------------
console.log("--- Demo 3 - Score Calculator ---");
let score1 = parseFloat(prompt("Enter the score for game 1: "));
let score2 = parseFloat(prompt("Enter the score for game 2: "));
let score3 = parseFloat(prompt("Enter the score for game 3: "));
let totalScore = score1 + score2 + score3;
console.log(`Your total score for the three games is ${totalScore}!`);
alert("\nPress enter to continue...");
// -----------------------------------------------------------------------------
console.log("--- Demo 4 - Shopping Cart Subtotal ---");
let item1Price = parseFloat(prompt("Enter the price of the first item: "));
let item2Price = parseFloat(prompt("Enter the price of the second item: "));
let subtotal = item1Price + item2Price;
// There is a function for making the dollar amount go to two decimals.
// Try subtotal.toFixed(2) inside the string template.
console.log(`The subtotal for your two items is $${subtotal}.`);
alert("\nPress enter to continue...");
//

Task 5: Hours to Minutes Converter

1-7-numeric-input.js
console.log("--- Demo 1 - Age to Months Calculator ---");
// Convert input to a number in two steps (simple, but tedious).
let input = prompt("Enter your age:"); // 1) User types in age
let age = parseInt(input); // 2) Convert string input to an integer
console.log(`You are ${age} years old. That's ${age * 12} months old!`);
alert("\nPress enter to continue...");
// -----------------------------------------------------------------------------
console.log("--- Demo 2 - Square Area Calculator ---");
// Convert input to a number in one step
let length = parseFloat(prompt("Enter the length of the square: "));
let area = length * length;
console.log(`The area of the square is ${area}`);
alert("\nPress enter to continue...");
// -----------------------------------------------------------------------------
console.log("--- Demo 3 - Score Calculator ---");
let score1 = parseFloat(prompt("Enter the score for game 1: "));
let score2 = parseFloat(prompt("Enter the score for game 2: "));
let score3 = parseFloat(prompt("Enter the score for game 3: "));
let totalScore = score1 + score2 + score3;
console.log(`Your total score for the three games is ${totalScore}!`);
alert("\nPress enter to continue...");
// -----------------------------------------------------------------------------
console.log("--- Demo 4 - Shopping Cart Subtotal ---");
let item1Price = parseFloat(prompt("Enter the price of the first item: "));
let item2Price = parseFloat(prompt("Enter the price of the second item: "));
let subtotal = item1Price + item2Price;
// There is a function for making the dollar amount go to two decimals.
// Try subtotal.toFixed(2) inside the string template.
console.log(`The subtotal for your two items is $${subtotal}.`);
alert("\nPress enter to continue...");
// -----------------------------------------------------------------------------
console.log("--- Demo 5 - Hours to Minutes Converter ---");
let hours = parseFloat(prompt("Enter a number of hours: "));
let minutes = hours * 60;
console.log(`${hours} hours is equal to ${minutes} minutes.\n`);
//
divider

Sample Output

Your program output should something similar to the sample output below.

Sample Output
--- Demo 1 - Age to Months Calculator ---
Enter your age: 35
You are 35 years old. That's 420 months old!
Press enter to continue... [Enter]
--- Demo 2 - Square Area Calculator ---
Enter the length of the square: 11.5
The area of the square is 132.25
Press enter to continue... [Enter]
--- Demo 3 - Score Calculator ---
Enter the score for game 1: 45
Enter the score for game 2: 64
Enter the score for game 3: 99
Your total score for the three games is 208!
Press enter to continue... [Enter]
--- Demo 4 - Shopping Cart Subtotal ---
Enter the price of the first item: 12.50
Enter the price of the second item: 10
The subtotal for your two items is $22.5.
Press enter to continue... [Enter]
--- Demo 5 - Hours to Minutes Converter ---
Enter a number of hours: 12
12 hours is equal to 720 minutes.
divider

Reflection Questions

You may write your reflection answers as comments at the bottom of your code.

  1. Why is it important to convert user input from a string to a number before performing mathematical calculations, and what can happen if you don't?
  2. In what scenarios would you choose to use the parseInt() function versus the parseFloat() function? Give one specific example for each.
  3. Describe a real-world application or program you could create that would require using numeric input from a user. What data would you need to collect, and what calculations would you perform?
divider

Submission

Submit your activity and reflection answers to the appropriate dropbox.

Activity Complete