首页 文章

如果输入中没有小数点,则角度扩展货币管道输入不会格式化字符串/ int

提问于
浏览
0

如果数字是字符串格式且字符串中没有小数点,则Angular currency pipe不会将字符串/ int转换为货币格式 .

假设金额为12,我想显示12.00美元,如果通过“12”,则不显示但是如果12.00通过则其正常工作 .

//Code

import {Pipe, PipeTransform} from "@angular/core";
import {CurrencyPipe} from "@angular/common";
const _NUMBER_FORMAT_REGEXP = /^(\d+)?\.((\d+)(-(\d+))?)?$/;

@Pipe({name: 'myCurrency'})
export class MyCurrencyPipe implements PipeTransform  {
  constructor (private _currencyPipe: CurrencyPipe) {}

  transform(value: any, currencyCode: string, symbolDisplay: boolean, digits: string): string {
    if (typeof value === 'number' || _NUMBER_FORMAT_REGEXP.test(value)) {
      return this._currencyPipe.transform(value, currencyCode, symbolDisplay, digits);
    } else {
      return value;
    }
  }
}


@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <div>{{priceNoDecimal}}</div> {{priceNoDecimal | myCurrency}}
      <div>{{priceWithDecimal}}</div> {{priceWithDecimal | myCurrency}}      
    </div>
  `,
})
export class App {
  name:string;
  priceWithDecimal: string;
  priceNoDecimal: string;
  constructor() {
    this.name = 'Angular2',
    this.priceNoDecimal = "12"
    this.priceWithDecimal = "12.00"
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App , MyCurrencyPipe],
  providers: [CurrencyPipe],
  bootstrap: [ App ]
})
export class AppModule {}


//output

Hello Angular2

12
12
12.00
USD12.00

Plunker

2 回答

  • 1

    如果你看一下你应用的正则表达式: /^(\d+)?\.((\d+)(-(\d+))?)?$/ 它需要一个小数点 .

    以下正则表达式使小数点可选 /^(\d+)?\.?((\d+)(-(\d+))?)?$/

  • 1

    没有背景,这个问题可能不清楚 . 来自the previous answer的管道是正则表达式that is used in original number pipes来检测字符串中的数字:

    const _NUMBER_FORMAT_REGEXP = /^(\d+)?\.((\d+)(-(\d+))?)?$/;
    

    为了使其密切模仿input conditioning of original currency pipe,管道可能会更改为:

    function isNumeric(value: any): boolean {
      return !isNaN(value - parseFloat(value));
    }
    
    @Pipe({name: 'looseCurrency'})
    export class LooseCurrencyPipe implements PipeTransform {
      constructor(private _currencyPipe: CurrencyPipe) {}
    
      transform(value: any, currencyCode: string, symbolDisplay: boolean, digits: string): string {
        value = typeof value === 'string' && isNumeric(value) ? +value : value;
    
        if (typeof value === 'number') {
          return this._currencyPipe.transform(value, currencyCode, symbolDisplay, digits);
        } else {
          return value;
        }
      }
    }
    

    isNumeric 是从framework internals中提取的辅助函数 . 它应该work fine采用这种方法 .

相关问题