Angular : Is toFixed() functioning properly with one value but not with the other one?

My form has 2 inputs, each calling the calculeSalaire() function.

calculeSalaire()
{
  this.fraisGestion = this.getFraisGestion();
  this.tauxFraisGestion = this.getTauxFraisGestion();
  this.salaireBrut = this.getSalaireBrut();
  this.salaireNet = this.getSalaireNet();
  this.chargesSalariales = this.getChargesSalariales();
  this.chargesPatronales = this.getChargesPatronales();
  this.totalPaye = this.getTotalPaye();
}

All these functions return a number. I want to display only 2 decimal places for each of these values using the toFixed(2) function.

The formatting works for all functions except one:

getSalaireBrut()
{
   this.salaireBrut = (this.chiffreAffaire - this.fraisGestion - 
   this.fraisPro)/(1.10)/(1.447);

   var salaireBruttxt = this.salaireBrut.toFixed(2);

   return parseFloat(salaireBruttxt);
}

chiffreAffaire is an Input

fraisPro is an Input

fraisGestion is calculated

I'm puzzled why it doesn't work for this function but works fine in the following function:

getChargesSalariales()
  {
    this.chargesSalariales = this.salaireBrut*(23/100);
    var chargesSalarialtxt = this.chargesSalariales.toFixed(2);

    return parseFloat(chargesSalarialtxt);
  }

It's worth mentioning that I utilize the salaireBrut value calculated by the previous non-working function.

Any insights on why this discrepancy occurs?

Answer №1

When using the toFixed function, it's important to note that it returns a string rather than a number in order to prevent trailing zeros from being displayed. This is why the function may appear to be working correctly within your code (especially if you use a breakpoint), but when you subsequently use parseFloat, the value is converted back to a number without any trailing zeros.

To resolve this issue, make sure to return the value as a string and remove the parseFloat conversion step.

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

Is it possible to utilize terms such as 'calc' within the [style.width] directive?

Can I incorporate my variable into calc() within the [style.width] directive in angular? For example: <div [style.width.px]="calc(100% - myWidth)">some texts </div> ...

Utilizing BehaviorSubject to dynamically display components based on conditions

I have a basic Service that looks like this: import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs'; @Injectable() export class HighlightsService { private _highlightedTab: string = ''; highli ...

How to access type properties in typescript without using the "this" keyword

Below is a snippet of code that I am working with: class Player implements OthelloPlayer { depth; constructor(depth: number) { this.depth = depth; } getMove(state: OthelloState) { return this.MinimaxDecision(stat ...

What is the best way to convert a tuple containing key/value pairs into an object?

How can the function keyValueArrayToObject be rewritten in order to ensure that the type of keyValueObject is specifically {a: number; b: string}, instead of the current type which is {[k: string]: any}? const arrayOfKeyValue = [ {key: 'a', val ...

When restarting nginx, Angular fails to display the index page

On my VPS server, I have an application with the backend coded in node.js and the frontend in Angular. After restarting nginx, I encountered some issues where my API stopped working on HTTPS and only functioned on HTTP (previously, I was able to make requ ...

Errors may arise in Typescript when attempting to block the default behavior of DataGrid onRowEditStop

Hey there! I'm new to posting questions here and could use some help. I'm encountering a minor issue while trying to prevent the default behavior of the "Enter" key in the "onRowEditStop" method of the DataGrid component. Here's my code sni ...

Angular/NestJS user roles and authentication through JWT tokens

I am encountering difficulties in retrieving the user's role from the JWT token. It seems to be functioning properly for the ID but not for the role. Here is my guard: if (this.jwtService.isTokenExpired() || !this.authService.isAuthenticated()) { ...

What could be the reason for the failure of my class isInstance() check

Do you see any issues with the object being an instance of ChatRoom? Let me know your thoughts. Class: export class ChatRoom { public id?: number; public name_of_chat_room: string; public chat_creator_user_id: number; public chat_room_is_active: 0 ...

How does NgRx handle updating remote data once it has been modified?

I'm struggling to grasp the inner workings of NgRx. My user list is retrieved from a Firebase store using a service like this: getAllUsers():Observable<object>{ console.log('getAllUsers'); return this.afs.collection('us ...

Adding classes dynamically in Angular 2 app functionality

With this particular layout in mind: <li role="menu" class="drop-down"> <a class="drop-down--toggle"> <span class="flag-icon" [class]="_current.flag"//<-- don't work></span> </a> <ul class="drop-down--men ...

Tips on downloading an image using the URL in nestjs

I'm trying to retrieve a link and save the associated image in the static folder, but I seem to be encountering some issues with my code. Here's what I have so far: @Injectable() export class FilesService { createFileFromUrl(url: string) { t ...

Is there a way to consolidate two interface types while combining the overlapping properties into a union type?

Is there a way to create a type alias, Combine<A, B>, that can merge properties of any two interfaces, A and B, by combining their property types using union? Let's consider the following two interfaces as an example: interface Interface1 { t ...

The 'SVGResize' or 'onresize' property is not available on the 'SVGProps<SVGSVGElement>' type

Using React with SVG I'm facing an issue with handling the resizing event of an svg element. I have looked into using the SVGResize and onresize events, but encountered compilation errors when trying to implement them: const msg1 = (e: any) => co ...

An error has occurred in Angular2 and Ionic 2, where there is a TypeError preventing the reading of the property 'addEventListener' in the InAppBrowser

When attempting to open a remote address in my app using the Cordova plugin InAppBrowser, I encountered an issue with the following code: import { Injectable } from "@angular/core"; import { HttpQueryService } from "./httpqueryservice"; import { ToastCo ...

What is the most effective method for importing the "exceljs" library into an Angular project?

In my Angular 7 app, I am utilizing exceljs (https://www.npmjs.com/package/exceljs) to handle importing and exporting of Excel files. Currently, I have imported it using the following code snippet: import {Workbook} from "exceljs";. While it functions perf ...

Issue with readonly is preventing the ability to alter the font color of the input

I need to change the font color of a disabled input. When it is disabled, it appears gray and I want it to be black instead. I attempted to use readonly but that did not have the desired effect, and now the input is showing [object Object]. Below is my HTM ...

Enhancing view with Typescript progressions

My current view only displays a loader.gif and a message to the user. I am looking to enhance the user experience by adding a progress indicator, such as "Processing 1 of 50", during the data update process. The ts class interacts with a data service layer ...

Exploring Recursive Types in TypeScript

I'm looking to define a type that can hold either a string or an object containing a string or another object... To achieve this, I came up with the following type definition: type TranslationObject = { [key: string]: string | TranslationObject }; H ...

No input in ng2-select2

How can I reset the value in ng2-select2 by clicking on a button? Here is my current HTML code: <select2 id="bill" [data]="colBill" [options]="option" (valueChanged)="onBillArray($event);"> The corresponding Typescript code is: this.arrBill = []; ...

The Angular ViewportScroller feature appears to be malfunctioning in the latest release of Angular,

TestComponent.ts export class TestComponent implements OnInit, AfterViewInit { constructor( private scroller: ViewportScroller, ) {} scrollToAnchor() { this.scroller.scrollToAnchor('123456789'); } } HTM ...