Angular 5: How to Calculate the Sum of Two Numbers and Handle NaN Output

I have encountered an issue where I am trying to multiply two numbers and add another number, but the output is displaying as NaN. How can I troubleshoot and solve this problem?

Below is the code snippet:

medicines = [new Medicine()];

this.sum = 0;// sum variable is also of type number

for (let i = 0; i < this.medicines.length; i++)
{
    this.sum = this.sum + this.medicines[i].price * this.medicines[i].quantity;// both price and quantity are of type number
    console.log(typeof this.sum);// however, it prints NaN
}

Model for medicines:

export class Medicine{
   constructor(){}
   name: String;
   quantity: number;
   price: number;
}

Answer №1

Here is an example of what it could look like:

prescriptions:Prescription[]=[{name: 'medication1', quantity:3, price:6},{name: 'medication2', quantity:5, price:10}]

or:

prescriptions: Array<Prescription> = new Array<Prescription>();

Answer №2

Is it possible to achieve something like this?

this.sum = this.sum + +this.medicines[i].price * +this.medicines[i].quantity;

Add a + before the property, this way it will convert the property value to a number if it is not already a number.

Answer №3

prescriptions: [] = new Prescription();

totalCost = 0;// totalCost is a number data type
for (let j = 0; j < this.prescriptions.length; j++)
{
    this.totalCost = this.totalCost + this.prescriptions[j].cost * this.prescriptions[j].quantity;// cost and quantity are both numbers
    console.log(typeof this.totalCost);// the result prints as NaN, which is unexpected
}

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

Upgrading to Angular 14 has caused issues with component testing that involves injecting MAT_DIALOG_DATA

After upgrading Angular from 14.1.1 to 14.2.10 and Material from 14.1.1 to 14.2.7, a peculiar issue arose when running tests with the default Karma runner. I am at a loss as to what could have caused this problem, so any advice would be appreciated. The u ...

Why is the data from an Angular service returning as undefined when I call it from a component?

Currently, I'm utilizing the JSONPlace holder Fake API to retrieve data. Despite successfully fetching the data in my service, when I attempt to call that service from my app component, I am encountering an issue where it returns undefined. What could ...

Creating generic types for a function that builds <options>

I have encountered a situation in my application where I need to loop through an array to construct a list of <option> tags. To streamline this process, I am attempting to create a universal function. function optionValues<T, K extends keyof T> ...

Issues with installing dependencies in Angular 2 through npm

While developing my Angular 2 application locally, everything was working smoothly. However, when I tried to deploy it to the server without the node_module folder and then did a npm install followed by a build, my app just kept showing "Loading..." withou ...

Using Angular 2 to access information from the OpenWeather API

Trying to integrate weather data from an openweather API has presented a challenge. The object received contains an array of 40 objects representing the weather forecast for the next 5 days with a 3-hour interval. The issue lies in displaying this 5-day fo ...

How to specify a single kind of JavaScript object using Typescript

Let's say we have an object structured as follows: const obj = [ { createdAt: "2022-10-25T08:06:29.392Z", updatedAt: "2022-10-25T08:06:29.392Z"}, { createdAt: "2022-10-25T08:06:29.392Z", animal: "cat"} ] We ...

Exporting numerous modules from an NPM package

Currently, I am working on a large Node and Typescript project called Project A. This project consists of numerous modules that I intend to reuse in another project, Project B. In order to achieve this reusability, I have configured the tsconfig.json file ...

Pinia store encountering a Typescript Vue component issue: error message "The property 'testStore' does not exist on the 'CreateComponentPublicInstance' type."

Within my <script setup> block, I have imported my testStore. However, whenever I attempt to use this.testStore.name in my Vue file, Vetur displays the following error: Property 'testStore' does not exist on type 'CreateComponentPublic ...

Ways to retrieve root context within a Vue Composition API in Vue 3.0 + TypeScript

Looking to develop a TypeScript wrapper function that can trigger toast notifications using a composition function, following the guidelines outlined in Vue 3.0's Composition API RFC. In this instance, we are utilizing BootstrapVue v2.0 for toast not ...

The error code TS2554 is triggered when 5 arguments are passed instead of the expected 3-4

I'm utilizing the gsap plugin to craft a captivating text animation effect. As I reached the last line of code in my 'animation_text_1' function, specifically where it states "TweenMax.staggerFromTo(.....)", an error cropped up which read: ...

When faced with the error message "Typescript property does not exist on union type" it becomes difficult to assess the variable

This question is a continuation of the previous discussion on Typescript property does not exist on union type. One solution suggested was to utilize the in operator to evaluate objects within the union. Here's an example: type Obj1 = { message: stri ...

To switch to desktop mode, double click; for mobile view, just tap once

I am looking to implement 2 different gestures for a specific feature in my application. Ideally, I want users to be able to double click on a card to open it in desktop view, but if they are using a phone, a single tap should suffice. How can I achieve th ...

Is it possible to deduce Typescript argument types for a specific implementation that has multiple overloaded signatures?

My call method has two signatures and a single implementation: call<T extends CallChannel, TArgs extends CallParameters[T]>(channel: T, ...args: TArgs): ReturnType<CallListener<T>>; call<T extends SharedChannel, TArgs extends SharedPar ...

Creating a JSON schema for MongoDB using a TypeScript interface: a step-by-step guide

In order to enhance the quality of our data stored in MongoDB database, we have decided to implement JSON Schema validation. Since we are using typescript in our project and have interfaces for all our collections, I am seeking an efficient method to achie ...

Utilizing Firebase 3 with Ionic 2 and cordova-plugin-camera for seamless file uploading

I have been attempting to upload images to Firebase storage using the cordova-plugin-camera but have not been successful: Below is the code I have been using: let options:any = { quality : 100, destinationType : Camera.DestinationType.DATA_URL, ...

Establish a connection to Cosmos DB from local code by utilizing the DefaultAzureCredential method

I've created a Typescript script to retrieve items from a Cosmos DB container, utilizing the DefaultAzureCredential for authentication. However, I'm encountering a 403 error indicating insufficient permissions, which is puzzling since I am the ad ...

Assign a predetermined value to a dropdown list within a FormGroup

I have received 2 sets of data from my API: { "content": [{ "id": 1, "roleName": "admin", }, { "id": 2, "roleName": "user", }, { "id": 3, "roleName": "other", } ], "last": true, "totalEleme ...

Creating a function in Ionic 2: A step-by-step guide

I'm having trouble defining a simple function in Ionic 2. Here is the code I am struggling with: import { Component } from '@angular/core'; import { NavController, NavParams } from 'ionic-angular'; @Component({ selector: &a ...

Connecting JavaScript files in angular 4: A step-by-step guide

Currently, I am utilizing Angular 4 and looking to have my JavaScript file work globally. Here is how I have declared it in the index.html file: <script src="assets/js/jquery-1.11.1.min.js"></script> <script src="assets/js/bootstrap.min.js"& ...

What is the recommended approach in Angular for unassigned @Input() variables when using TypeScript strict mode?

Issue at Hand After upgrading my Angular version from 10 to 13, I encountered a problem with the new TypeScript strict compiler mode. The upgrade required me to assign values to all declared variables upon initialization, causing issues with properties de ...