【问题标题】:How to replace dot with comma on input?如何在输入时用逗号替换点?
【发布时间】:2023-03-23 21:17:01
【问题描述】:

我正在尝试在我的 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
  }
}

但它只是在 parseFloat 上返回 NaN 值并将输入设置为 1...

【问题讨论】:

    标签: angular typescript angular-directive


    【解决方案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 和其他内置数字formatters,它们可以处理货币和语言等内容。

    【讨论】:

      猜你喜欢
      • 2021-11-06
      • 2017-06-09
      • 1970-01-01
      • 2014-02-21
      • 1970-01-01
      • 2016-09-05
      • 2018-07-06
      • 2015-09-20
      • 1970-01-01
      相关资源
      最近更新 更多