打字稿减法不按预期方式工作

打字稿减法不按预期方式工作

问题描述:

我有一个包含增值税的全部金额,我想分离净价格和增值税。打字稿减法不按预期方式工作

这个例子的最终价格是80.60,增值税是24%。净价和什么是增值税? 答案应该是净价格是65.00,增值税= 15.60。

由于某些原因,typescript计算65.00和15.599999999999994。 目前我不想四舍五入,但结果应该是15.60。 我知道有关于如何计算增值税的其他ansers,但我的问题是非常具体什么是我的代码错误,并生成这个十进制而不是15.60。

这里是我的代码: 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> 
+0

这很常见。有关浮点舍入错误的一个解释,请参阅此处:https://stackoverflow.com/questions/588004/is-floating-point-math-broken –

+0

那么有什么我可以做我的代码来解决它? –

+0

您可以舍入或截断为小数点。你可以在这里看到一些其他的想法:https://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript –

这是因为我们认识到十进制数进行编码,并存储在二进制文件。通常十进制数不能用二进制精确表示,所以会有舍入误差。

看起来你只需要将数字格式化为2位小数。

你有几个选项来做到这一点:

  • 您可以使用内置在JavaScript号方法,toFixed(2)(see MDN docs)在你的控制器逻辑格式化减为2位小数的结果。

  • 您可以使用角DecimalPipe在你的控制器逻辑:(see Angular docs)

    /* 
        The Angular DecimalPipe can be more useful that toFixed() 
        because it has a wider number of formatting options including 
        the setting both the minimum and maximum number of digits after 
        the decimal point. In this case it's specified a minimum AND 
        maximum of 2 decimal places. 
    
        Because decimals can be represented differently in different 
        countries, the DecimalPipe constructor takes a locale. 
    */ 
    const locale = 'en-US'; 
    const decimalPipe = new DecimalPipe(locale); 
    this.fpaValue = decimalPipe.transform(this.totalPrice - this.netPrice, '.2-2'); 
    
  • 如果你在你的模板中其他显示fpaValue,那么你可以在模板中使用十进制管:

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

首先,它不是TypeScript的问题。它的浮点的行为JS:http://floating-point-gui.de/

用途:

this.fpaValue.toFixed(2); 

,你会得到你的答案高达2个小数点。