Performing mathematical calculations with numerical values

This piece of code was created as a component of a calculator project for learning purposes. It functions correctly for the most part.

However, I noticed that the addition operation seems to concatenate the two numbers together instead of actually adding them. Why is this happening?

function calcApp (aNumber, bNumber) {
    var a = prompt("Enter A number :");
    var b = prompt("Enter B number :");
    var mathSign = prompt("Enter Math Sign :");

    aNumber = a;
    bNumber = b;

    if (mathSign == "+") {
        alert(a + b);
    }
    else if (mathSign == "-") {
        alert(a - b);
    }
    else if (mathSign == "*") {
        alert(a * b);
    }
    else if (mathSign == "/") {
        alert(a / b);
    }
    else {
        prompt("Enter a valid Math sign!!")
    }
}
calcApp();

Answer №1

prompt is a function that returns a string value. When you use the + operator on strings, they get concatenated together.

To convert the user's input into a number, there are several methods you can use:

var userInput = '6.8';

console.log(parseInt(userInput, 10)); // converts to integer
console.log(parseFloat(userInput)); // converts to float
console.log(+userInput);
console.log(Number(userInput));

Answer №2

prompt will provide a string as the input. It is necessary to convert this string into a number.

To achieve this, you can utilize the Number object for converting the string to a numerical value.

When using the Number object, make sure to watch out for occurrences of NaN (Not-A-Number). For instance, Number('55 abc') results in NaN.

Exercise caution when employing parseInt since it eliminates decimal numbers. For example, parseInt('12.99') returns 12.

Below is your updated code incorporating the use of the Number object,

function calcApp (aNumber, bNumber) {
    var a = prompt("Enter A number :");
    var b = prompt("Enter B number :");
    var mathSign = prompt("Enter Math Sign :");

    aNumber = a;
    bNumber = b;

    //Convert to number
    a = Number(a); <----------
    b = Number(b); <----------

    if (mathSign == "+") {
        alert(a + b);
    }
    else if (mathSign == "-") {
        alert(a - b);
    }
    else if (mathSign == "*") {
        alert(a * b);
    }
    else if (mathSign == "/") {
        alert(a / b);
    }
    else {
        prompt("Enter a valid Math sign!!")
    }
}
calcApp();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with data entry: unable to enter the letter 'S' in search field

This bug has been a real challenge for me. It's strange, but I'm unable to type the letter "S" into the search input field. Oddly enough, the keyboard seems to be functioning properly. Please find the sandbox below for reference: https://codes ...

"Can someone guide me on the process of transmitting data to a client using Node in combination with

I am new to web development and struggling to understand how to transfer data from the Node server to the client while also displaying an HTML page. I am aware that res.send() is used to send data, but I'm having difficulty maintaining the client disp ...

Exploring the JSON data in Javascript using Ajax

Completely new to Javascript, I am just trying to grasp the basics of the language. Currently, I have a JSON request set up with the following code: function request(){ $.ajax({ dataType: "jsonp", type: 'GET', url: "getWebsite", ...

Accessing information from Firebase and displaying it within an Angular Controller

As a newcomer to the latest Firebase SDK (with some experience using angularfire), I set out to retrieve data and display it using Angular. This is my progress so far: var app = angular.module('dApp',[]); app.controller('listingControler&a ...

Eliminating the glow effect, border, and both vertical and horizontal scrollbars from a textarea

Dealing with the textarea element has been a struggle for me. Despite adding decorations, I am still facing issues with it. The glow and border just won't disappear, which is quite frustrating. Could it be because of the form-control class? When I rem ...

The Ajax form is failing to send any headers

Whenever I submit my form, the header data doesn't seem to be coming through. Even though I've done this type of submission numerous times (figuratively speaking), there's always a chance that I might be overlooking something. Any ideas? Che ...

What is the process for retrieving wallet transactions using Alchemy websockets?

I am trying to retrieve all new transactions from a specific wallet using the code provided. However, I am encountering an issue when using the function tx["transaction"]["from"] to filter transactions based on the specified wallet. I am utilizing Alchemy ...

The removal of an object becomes unsuccessful when objects with lower indices have been deleted beforehand

Attempting to construct a multi-layer object representing a program; check out my progress here http://codepen.io/Irish1/pen/lbjdw Imagine adding 3 weeks, each with 3 days, and each day having 3 sessions. Removing these objects is feasible as long as caut ...

AngularJS: Unable to locate element using getElementById function

Using a third party JavaScript application, I have integrated and invoked a function within one of my AngularJS factories. This function requires the id of a DOM element as a parameter, as it manipulates this element. ThirdPartyApp.doSomething("#elementId ...

Debugging in Javascript involves pausing or breaking at every instance of a javascript function being called

I am currently working on unraveling a complex legacy JavaScript codebase, and I'm finding it challenging to determine where to place breakpoints (having to locate the files and set a breakpoint in Firebug, etc). Is there a way for Firebug to automat ...

Utilize interpolation with ES6 and an Angular 1.4 directive

Currently experimenting with the unique ES6 + Angular combination and facing a challenge in interpolating an html string within a directive that includes scope bindings. We have attempted the following approach: Current scenario The code below is functi ...

The provisional headers provided by the local passport authentication strategy offer an added layer

When I send a POST request from my frontend with a username and password object, here is the code: const login = data => ( axios.post('http://localhost:3000/v1/user/login', data) .then(response => response.data) .catch((err) => ...

Is there a way to send an AJAX request to an MVC action from a JavaScript file?

In a file named job.js, there is code that works perfectly when run on localhost but results in a 404 error when run on an intranet server with an application name. Job.updateJob = function () { $.post('/Builder/ListJobItems', function (dat ...

What is the process for decoding HTML content that is wrapped within JSON data?

I have a web application built using asp.net that utilizes ajax calls. Below is the code snippet for my web method which successfully responds to the ajax call. ADController adc = new ADController(); DataTable dt = adc.GetGeneral(Convert.ToInt32(A ...

Comparing npm install --save versus npm install --save-dev

Hey everyone, I've been using npm install -g to globally install node modules/packages, but I'm a bit confused about the --save and --save-dev options. I tried looking it up on Google, but I'm still not entirely sure. Can you guys help clar ...

Issues with LocalStrategy not executing in passport authentication

I am currently facing an issue with authenticating using Passport and LocalStrategy. It seems like the strategy is not being called and when I log the user object in passport.authenticate, it returns "false". Below is my client-side code: logIn = () =& ...

Tips on transmitting and receiving substantial JSON information

As a newbie in the full-stack development world, I am currently on a quest to find an efficient method for transmitting and retrieving large data between my React front-end and Express back-end while keeping memory usage to a minimum. My project involves b ...

Dividing JSON information into parts

I am attempting to present a highchart. I have utilized the following link: Highchart Demo Link Now, I am trying this web method: [WebMethod] public static string select() { SMSEntities d = new SMSEntities(); List<str ...

Unable to access property 'map' of undefined - error occurred while processing JSON data in line test.js:11

I'm attempting to utilize the json file in the test component below, but I keep encountering the error: TypeError: Cannot read property 'map' of undefined. I have modified the file within the test.js component, and when testing it with a sa ...

How come the array's length is not appearing on the browser screen?

Code: initialize: function() { this.todos = [ {id: 100, text: 'Rich'}, {id: 200, text: 'Dave'} ]; }, activeTodos: function() { this.todos = this.todos.length(function() { return this.todos; }); ...