2017-12-03 83 views
0

我有一個包含增值稅的全部金額,我想分離淨價格和增值稅。打字稿減法不按預期方式工作

這個例子的最終價格是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 –

回答

0

這是因爲我們認識到十進制數進行編碼,並存儲在二進制文件。通常十進制數不能用二進制精確表示,所以會有舍入誤差。

看起來你只需要將數字格式化爲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' }} 
    
0

首先,它不是TypeScript的問題。它的浮點的行爲JS:http://floating-point-gui.de/

用途:

this.fpaValue.toFixed(2); 

,你會得到你的答案高達2個小數點。