Converting a string to a number is not functioning as expected

I am facing a problem with an input shown below. The issue arises when trying to convert the budget numeric property into thousands separators (for example, 1,000).

<ion-input [ngModel]="project.budget | thousandsSeparatorPipe" 
(ngModelChange)="project.budget=$event;calculateContingency()" 
    formControlName="budget" type="text"></ion-input>

Unfortunately, it does not seem to be working as expected:

calculateContingency(eve:any) {
   this.project.contingency = ((Number(this.project.budget) * this.project.contingencyPercentage) * 1 / 100);
    this.changeDetectorRef.detectChanges();
  }

The output appears like this:

https://i.sstatic.net/g9WeW.png

Could you advise me on how to resolve this issue? Alternatively, is there a way to use the budget model without the thousand separators? If so, I can then pass it to the calculation method mentioned above.

Answer №1

Utilize the parseFloat function alongside a regular expression to substitute out any commas,

 this.project.contingency = ((parseFloat(this.project.budget.replace(/,/g, '')) * this.project.contingencyPercentage) * 1 / 100);

EXAMPLE

var budget = '1,000';
var buget2 = 1000;
var contigency = parseFloat(budget.replace(/,/g, '')) + buget2;
console.log(contigency);

Answer №2

To successfully convert a string to a number, first remove the comma using STRING.replace(',',''). This simple trick should do the job perfectly.

Here's an example:

    updateBudget(event: any) {
   this.totalBudget = ((Number(this.project.budget.replace(',','')) * this.project.percentage) / 100);
    this.changeDetectorRef.detectChanges();
  }

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

Tips for incorporating an outside model into vue.js with babylon js

Struggling with importing a gltf file into vue.js using babylon.js to create a 3D view on a webpage. The documentation online isn't very clear, and I've tried the following steps in my Hello.vue file: <div> <h1> Hello </h1> < ...

Encounter issue when using GAS withSuccessHandler function

I've developed a Google Sheets add-on that utilizes a modal dialog for the user interface. I encountered an issue with the success handler not running as expected, so I created a basic test interface to troubleshoot the problem. After the server-side ...

Error: The method By.cssSelector is invalid and cannot be used

Currently utilizing npm's Selenium Webdriver. Having difficulty getting By.cssSelector to function properly. Other selectors like By.tagName and By.id are working fine. Here is the code snippet: var webdriver = require('selenium-webdriver&apos ...

Avoid opening the page when attempting to log in with jquery, ajax, and php

I am facing an issue with my code. I have a file named "index.html" which contains a login form. Another file called "dash.js" retrieves the username and password from the login form and redirects to "connectdb.php" to check the login credentials with the ...

Using Selenium WebDriver to handle Angular requests in Java

I am currently developing tests for an angular-based application and I find myself in need of assistance. The specific task at hand involves creating a mechanism that will wait until all pending requests within the application have been processed before pr ...

Creating a JSON-based verification system for a login page

First time seeking help on a programming platform, still a beginner in the field. I'm attempting to create a basic bank login page using a JSON file that stores all usernames and passwords. I have written an if statement to check the JSON file for m ...

Is there a way to transform a large gltf file into jsx format?

I recently created a 3D scene in Blender and wanted to incorporate it into my React Three Fiber project. However, after exporting the scene to glTF format, I discovered that the file contained around 300k lines. The strange thing is that the file works per ...

Steps for connecting to a property in another component

As a newcomer to Angular, I am exploring new concepts for the first time. I have a custom component called Timeselector with an Apply button whose enable/disable state is determined by validations performed in another custom component called Monthpicker. C ...

Webpage refreshing when resizing browser

Hey there, I'm facing an issue where my HTML website restarts whenever the browser size changes. Can someone please help me fix this? You can check out my website here I have uploaded my code files here: Code Files Link ...

React SlideMenu will not close when a link is clicked

I am facing an issue with my off-canvas menu, which slides in when the variable isOpen is set to true. However, the problem arises when trying to slide it back out upon clicking a Link to navigate to another page. Instead of sliding out, the mobile menu oc ...

Angular2: How to deactivate a specific element in a form created with formbuilder

After initializing my formbuilder, I need to disable a specific element because I need to perform some validation once the view is loaded. Here is how I declared my formBuilder. ionViewDidLoad() { this.purchaseDataForm = this.formBuilder.group({ kms ...

Dealing with complications in the Rails asset pipeline management

I am working on a webpage that requires real-time data to be displayed. Therefore, it necessitates continuous ajax communication post page load. similar to this, jQuery -> setInterval -> $.ajax url: "some url" success: (data, te ...

Looking to showcase more detailed items within ng-repeat in AngularJS

Retrieve an object from the server that resembles the following structure: "courses": [ { "id": 1, "name": "piano", "classes": [ { "id": 1, "name": "piano1", }, { ...

Struggling with replacing text in an array using Javascript (Angular)

I am facing an issue where I need to remove the 'hello' substring from each object field in my objects array. However, I keep getting an error message saying "Cannot read property 'indexOf' of null". This error is occurring because I am ...

"Return to previous page" feature

I am having difficulty figuring out how to implement the "go back" function for the page. For instance, I have pages A, B, C, and D. The possible switching between pages is as follows: A -> (B <-> C) -> A or D -> (B <-> C) -> D (w ...

Navigating to a precise location on initial page load using Angular 11

Within the structure of my app, I have a parent component that displays a large image from a child component. When the parent component loads, I want the browser window to automatically scroll to a specific position in order to center the image. Currently ...

You have attempted to make an invalid hook call in the react chat app. Hooks can only be called within the body of a function component

Encountering problems like manifest.json:1 Manifest: Line: 1, column: 1, Syntax error. **Important Error Message/User Notification:** react-dom.development.js:20085 The above error occurred in the <WithStyles(ForwardRef(AppBar))> component: Arrange ...

I need to find a way to identify when empty JSON data is being submitted to my RESTful HTTP POST endpoint. This issue is causing

I've set up a REST endpoint to handle JSON data sent via an HTTP post request using XMLHttpRequest as my client. Everything seems to be working smoothly until I wanted to test how the server would handle receiving no data at all, specifically null. To ...

Is it possible to obtain a return value from Electron's webContents.executeJavaScript when NodeIntegration is disabled?

Is there a way to retrieve a return value without using NodeIntegration in Electron, similar to ipcRenderer when it's enabled? ...

Dealing with an empty req.body in an Express.js POST request

Having trouble solving this issue with a simple search. Can anyone provide clearer guidance? In the client-side code, I attempted to attach an object using xhr.send(obj). Currently, I'm trying to append to the formData object, but the result remains ...