如何在输入中用逗号替换点?

How to replace dot with comma on input?

我正在尝试在我的 Angular 应用程序中使用指令,在输入框中,用户必须只能插入小数点后三位的值。

小数点用逗号分隔,但在某些情况下,用户可能会使用点作为分隔符,在这种情况下,我必须在输入时用逗号替换点。

我正在尝试以下方式来实现它:

@Directive({
  selector: '[appQuantity]',
})
export class QuantityDirective {
  @Input()
  public plu: Plu;

  constructor(private ref: ElementRef) {}

  @HostListener('input', ['$event'])
  public onInput(event: any): void {
    const val = this.ref.nativeElement.value;

    this.ref.nativeElement.value = this.ref.nativeElement.value.replace(/\./g, ','); // here i should replace dot with comma but it's not working
    if (this.plu.um === 'PZ'){ // controls if input is empty i'm setting 1
      if (!val || val <= 0){
        this.ref.nativeElement.value = 1;
      }
    }
    this.plu.qta = parseFloat(this.ref.nativeElement.value); // setting the object quantity to inserted value
  }
}

但它只是 return parseFloat 上的 NaN 值并且只是将输入设置为 1...

根据 parseFloat 的文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat

Return value
A floating point number parsed from the given string.

Or NaN when the first non-whitespace character cannot be converted to a number.

Parsefloat 需要一个字符串 000.00 但因为您将 . 替换为 , 您得到的是 NaN。

我建议先解析数字,然后转换为您的输出,并且只在您对值感到满意后才进行设置,而不是多次重置相同的值。

@Directive({
  selector: '[appQuantity]',
})
export class QuantityDirective {
  @Input()
  public plu: Plu;

  constructor(private ref: ElementRef) {}

  @HostListener('input', ['$event'])
  public onInput(event: any): void {
    // Use `let` instead of rewriting the value constantly (weird side effects on ui if you keep setting the value)
    let val = this.ref.nativeElement.value;

    // Convert `,` to `.` to allow for valid parsing
    val = parseFloat( val.replace(/,/g, '.'))
    if (this.plu.um === 'PZ'){ // controls if input is empty i'm setting 1
    // Now that `val` is a number, `<= 0` is valid because it should not be used on strings
      if (!val || val <= 0){
        val = 1;
      }
    }

    // Format as needed
    const correctFormat = val.toString().replace(/\./g, ',')
    // Set now
    this.ref.nativeElement.value = correctFormat
    this.plu.qta= correctFormat; // setting the object quantity to inserted value
  }
}
只是一个小费

如果您担心数字格式,可以使用 toLocaleString and other built in number formatters 来处理货币和语言等内容。