我有一個包含增值稅的全部金額,我想分離淨價格和增值稅。打字稿減法不按預期方式工作
這個例子的最終價格是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>
這很常見。有關浮點舍入錯誤的一個解釋,請參閱此處:https://stackoverflow.com/questions/588004/is-floating-point-math-broken –
那麼有什麼我可以做我的代碼來解決它? –
您可以舍入或截斷爲小數點。你可以在這裏看到一些其他的想法:https://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript –