我有包含增值税的全额金额,我想将净价和增值税分开。
示例最终价格为 80.60,增值税为 24%。净价是多少,增值税值是多少? 答案应该是净价是 65.00,增值税值 = 15.60。
出于某种原因, typescript 计算出 65.00 和 15.599999999999994。 目前我不想四舍五入,但结果显然应该是 15.60。 我知道还有其他关于如何计算 Vat 的答案,但我的问题非常具体,我的代码出了什么问题,生成了这个小数而不是 15.60。
这是我的代码: 组件.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;
}
}
组件.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>
最佳答案
这是因为我们所认识的十进制数是用二进制编码和存储的。通常十进制数无法用二进制精确表示,因此存在舍入误差。
看起来您只需将数字格式化为小数点后两位。
您有几种选择可以做到这一点:
您可以使用内置的 JavaScript Number 方法,
toFixed(2)
:(see MDN docs)在 Controller 逻辑中将减法结果格式化为小数点后两位。您可以在 Controller 逻辑中使用 Angular 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' }}
关于angular - typescript 减法未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47617034/