打字稿减法无法按预期工作

时间:2017-12-03 09:28:17

标签: angular typescript

我有全额包括增值税,我想分开净价和增值税。

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

由于某种原因,打字稿计算65.00和15.599999999999994。 目前我不想圆,结果应该是15.60清楚。 我知道还有其他的关于如何计算增值税的问题,但我的问题非常具体,我的代码是错误的,并生成了这个小数而不是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>

2 个答案:

答案 0 :(得分:0)

这是因为我们认为十进制数字被编码并以二进制形式存储。通常十进制数不能精确地以二进制表示,因此存在舍入误差。

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

你有几个选择:

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

  • 您可以在控制器逻辑中使用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' }}
    

答案 1 :(得分:0)

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

使用:

cross_val_score function

您将得到最多2位小数的答案。

相关问题