Having trouble with Typescript subtraction yielding unexpected results?

If I have a total amount including VAT and want to separate the net price and the VAT value, how can this be done?

For example, if the final price is $80.60 with a VAT rate of 24%, what would be the net price and the VAT value? The correct answer should show the net price as $65.00 and the VAT value as $15.60.

I'm having an issue where typescript calculates the VAT value as 15.599999999999994 instead of rounding it to 15.60. Although there are other methods to calculate VAT, my main concern is why my code is generating this lengthy decimal.

Here is the code in question: component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-fpa',
  templateUrl: './fpa.component.html',
  styleUrls: ['./fpa.component.css']
})
export class FpaComponent implements OnInit {

    public netPrice:number;
    public fpaPercent:number=24;
    public fpaValue:number=0;
    public totalPrice:number;

public calc(calcType:string = ''){
    this.netPrice = this.totalPrice / ((this.fpaPercent/100)+1);
    this.fpaValue = this.totalPrice - this.netPrice;
}

}

component.html

                   
                        <mat-form-field>
                            <input [(ngModel)]="netPrice" (keyup)="calc('byNetPrice');" matInput placeholder="Net Price">
                        </mat-form-field>

                        <mat-form-field>
                            <input [(ngModel)]="fpaPercent" (keyup)="calc();" matInput placeholder="% Vat">
                        </mat-form-field>

                        <mat-form-field>
                            <input [(ngModel)]="fpaValue" (keyup)="calc('byFpaValue');" matInput placeholder="VAT Value">
                        </mat-form-field>

                        <mat-form-field>
                            <input [(ngModel)]="totalPrice" (keyup)="calc('byFinalPrice');" matInput placeholder="Final Price" >
                        </mat-form-field>

Answer №1

The reason for discrepancies in decimal numbers when converted to binary is due to the inherent limitations of binary encoding. It often leads to rounding errors.

To solve this issue, you can easily format the number to two decimal places.

There are multiple approaches you can take:

  • You may utilize the built-in JavaScript Number method, toFixed(2), within your controller logic to ensure the subtraction result is formatted to two decimal places. Check out the MDN docs for more information.

  • Alternatively, consider using the Angular DecimalPipe in your controller logic as shown below. Refer to the Angular documentation for detailed guidance:

    /*
        The Angular DecimalPipe provides a range of formatting options,
        allowing you to specify both minimum and maximum digits after
        the decimal point. In this scenario, we're setting it to 2 decimal
        places.
    
        To cater to regional differences in number representation,
        the DecimalPipe constructor requires a locale parameter.
    */
    const locale = 'en-US';
    const decimalPipe = new DecimalPipe(locale);
    this.fpaValue = decimalPipe.transform(this.totalPrice - this.netPrice, '.2-2');
    
  • If you intend to display the fpaValue in another section of your template, incorporate the decimal pipe directly within the template as demonstrated below:

    {{ fpaValue | number:'.2-2' }}
    

Answer №2

Initially, the issue lies not with TypeScript but with how Floating Point works in JavaScript:

To resolve this, you can utilize the following code snippet:

this.fpaValue.toFixed(2);

By doing so, you will obtain your result rounded off to 2 decimal places.

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

Error: Angular encountered an issue while loading the resource. Preflight response was not successful

I am attempting to send a request to an API endpoint using Angular in order to retrieve JSON data. Check out my code snippet below: import { Component, OnInit } from '@angular/core'; import {HttpClient} from '@angular/common/http'; imp ...

Is there a way to automatically validate v-forms inside a v-data-table when the page loads?

In my data entry form, I have utilized a v-data-table with each column containing a v-form and v-text-field for direct value updates. My goal is to validate all fields upon page load to identify any incorrect data inputs. However, I am facing challenges in ...

What's causing this issue in Angular?

In this scenario, there is a parent component and a child component communicating with each other. The parent component passes a method to the child component, which the child component then calls and sends its own instance back to the parent. However, wh ...

The absence of @angular/compiler in the bundle file is causing an issue with Angular es

I've developed a shell application that operates using and https://github.com/systemjs/systemjs to manage its various micro-frontends. Recently, I created a new Angular application and aimed to integrate it with the esBuild builder tool. Upon runni ...

Steps for resolving the problem of the Express error handler not being executed

This question has come up again, and I have searched for solutions but none seem to work. Your assistance in debugging the issue would be greatly appreciated. I have a separate errorHandler set up as middleware. In my error-handler.ts file: import expres ...

Import resolves Uncaught ReferenceError by preventing access to 'xx' before it is initialized

Currently, I am troubleshooting a peculiar error that has come up. Within my service file where all other services are stored, I have included the import of one component along with all the other services required by the frontend. import { VacationComponen ...

Troubleshooting Angular 2 RC5: detectChanges function not functioning as expected

Currently, I am working on developing a login form component that has the following interface: <login-form onlogin="submit()"></login-form> Here is the testing code for this component: it("Ensuring credentials are passed correctly out of t ...

Tips for validating Angular form group input depending on the value of another input within the form?

I am facing an issue with form validation in my Angular version 8 application. I need to validate a form based on the following rules: If a file is uploaded (even if just clicking the button without selecting a file), then the Reason input is not required ...

Angular 6 form controls with reactive elements

Looking to create a simple homepage using Angular 6. One of the features will include tests for prime factorization and leap years, implemented with reactive forms for validation. However, I am facing an issue where I cannot execute both functions simultan ...

Issue: Failed to locate module @angular/core

When attempting to run an Angular 4 application, I consistently encounter the following error: ERROR in Could not resolve module @angular/core There are no additional errors present. There are no dependency issues whatsoever as @angular/core is located i ...

Creating a spy object in Jasmine for the forEach method of router.events

I have been attempting to create a test case for a component in an application and am having trouble with the constructor. Here is how it looks: constructor(private router: Router, public dialog: MatDialog, private tlsApiServi ...

Acquiring the Auth0 authentication token

Currently, I am using the Angular SDK of Auth0 and everything seems to be functioning correctly except for retrieving the token. At the moment, I am manually obtaining the token from my dashboard. The method in Auth0Service called getAccessTokenSilently i ...

Converting a React Typescript project to Javascript ES5: A step-by-step guide

I have a react typescript project and I need to convert the source code (NOT THE BUILD) to ES3 or ES5 JavaScript. This is because I want to use this code as a component in another React app. Can you suggest which preset and plugins I should use for this t ...

The constructor in a Typescript Angular controller fails to run

Once the following line of code is executed cockpit.controller('shell', shellCtrl); within my primary module, the shell controller gets registered with the Angular application's _invokeQueue. However, for some reason, the code inside t ...

Angular 2 view becomes unresponsive following navigation

I have a web application powered by an API using Angular 2. I implemented a global service that extends angular2-sails, which handles responses to API calls. If the response includes 401 PLEASE_LOGIN, it redirects the user to the signup component. The iss ...

Develop a TypeScript class that includes only a single calculated attribute

Is it advisable to create a class solely for one computed property as a key in order to manage the JSON response? I am faced with an issue where I need to create a blog post. There are 3 variations to choose from: A) Blog Post EN B) Blog Post GER C) Bl ...

Encountering a problem when parsing a JSON file in Angular 2

When attempting to access the config.json file in my Angular2 service, I have encountered an issue. load() { return new Promise((resolve, reject) => { this.http.get('./config.json') .map(res => res.json()) ...

What is the best way to seamlessly update a Redux state array in an immutable manner using Typescript?

I'm embarking on a journey to grasp Typescript through the creation of a simple Todo-List application. However, I've hit a roadblock in updating the Redux state array within a slice that I've established (or rather, I'm unsure how to go ...

What is the solution for resolving array items in a GraphQL query?

I am facing an issue with my graphql Query, specifically in trying to retrieve all the fields of a Post. { getSpaceByName(spaceName: "Anime") { spaceId spaceName spaceAvatarUrl spaceDescription followin ...

Tips for creating an API URL request with two search terms using Angular and TypeScript

I have developed a MapQuest API application that includes two input boxes - one for the "from" location and another for the "to" location for navigation. Currently, I have hardcoded the values for these locations in my app.component file, which retrieves t ...