问题
I want to display input and when user enters a number: 20
I want 20,00
to be displayed. For greater numbers I want to see thousand separator like 11 200,00
.
<input type="number" (ngModelChange)="calculateSum()" (change)="calculateAmount(invoiceQuota)" [ngModel]="invoiceQuota.controls.grossAmount.value">
I tried to add:
[ngModel]="invoiceQuota.controls.grossAmount.value | number:'1.2-2'
but it does not work
I can't find solution to solve my problem.
回答1:
import { Component, Input, NgZone, OnInit, Pipe, PipeTransform } from '@angular/core';
const PADDING = '00';
@Pipe({
name: 'floatNumber'
})
export class FloatNumnberPipe implements PipeTransform {
DECIMAL_SEPARATOR: string;
THOUSANDS_SEPARATOR: string;
constructor() {
// TODO comes from configuration settings
this.DECIMAL_SEPARATOR = '.';
this.THOUSANDS_SEPARATOR = ',';
}
transform(value: number | string, fractionSize: number = 2): string {
const ds = '.';
const ts = ',';
let [integer, fraction = ''] = (value || '').toString()
.split(ds);
fraction = fractionSize > 0
? ds + (fraction + PADDING).substring(0, fractionSize)
: '';
integer = integer.replace(/\B(?=(\d{3})+(?!\d))/g, ts);
integer = integer ? integer : '0';
return integer + fraction;
}
parse(value: string, fractionSize: number = 3): string {
const ds = '.';
const ts = ',';
let [integer, fraction = ''] = (value || '').split(ds);
integer = integer.replace(new RegExp(ts, 'g'), '');
fraction = parseInt(fraction, 10) > 0 && fractionSize > 0
? ds + (fraction + PADDING).substring(0, fractionSize)
: '';
integer = integer ? integer : '0';
return integer + fraction;
}
}
this way you can write float number PIPE and in component , if (typeof modelControlname === 'string') {
modelControlname=Math.round(Number(FloatNumnberPipe.prototype.parse(amount)) * 100) / 100);
modelControlname=FloatNumnberPipe.prototype.transform(modelControlname.value);
来源:https://stackoverflow.com/questions/51306811/angular-6-input-type-number-and-display-2-digits-after-comma