格式化货币输入的角度2 [英] Format currency input in angular 2

查看:69
本文介绍了格式化货币输入的角度2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在输入时将输入格式设置为美元货币.输入将有2个小数位,并且将从右至左输入. 假设我输入54.60,它将输入为$ 0.05-> $ 0.54-> $ 5.46-> $ 54.60.这个 PLUNKER 确实可以做到这一点,但是它在js上是有角度的.到目前为止,我的指令看起来像:

I want to format input to USD currency as you type. The input will have 2 decimal places and will enter from right to left. Suppose if I type 54.60 it will be entered as $0.05-->$0.54-->$5.46-->$54.60. This PLUNKER exactly does this, but its in angular js. So far my directive looks like:

import {Directive, Output, EventEmitter} from '@angular/core';
import {NgControl} from '@angular/forms';

@Directive({
  selector: '[formControlName][currency]',
  host: {
    '(ngModelChange)': 'onInputChange($event)',
    '(keydown.backspace)':'onInputChange($event.target.value, true)'
  }
})
export class CurrencyMask {
  constructor(public model: NgControl) {}

  @Output() rawChange:EventEmitter<string> = new EventEmitter<string>();

  onInputChange(event: any, backspace: any) {
    // remove all mask characters (keep only numeric)
    var newVal = event.replace(/\D/g, '');
    var rawValue = newVal;
    var str = (newVal=='0'?'0.0':newVal).split('.');
    str[1] = str[1] || '0';
    newVal= str[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1,') + '.' + (str[1].length==1?str[1]+'0':str[1]);



    // set the new value
    this.model.valueAccessor.writeValue(newVal);
    this.rawChange.emit(rawValue)
  }
}

并且在html中被用作:

and in html it is being used as:

<input  name="cost" placeholder="cost" class="form-control"  type="text" currency formControlName="cost" (rawChange)="rawCurrency=$event">

更新:

最终为我工作的是:

onInputChange(event: any, backspace: any) {
    var newVal = (parseInt(event.replace(/[^0-9]/g, ''))/100).toLocaleString('en-US', { minimumFractionDigits: 2 });
    var rawValue = newVal;

    if(backspace) {
      newVal = newVal.substring(0, newVal.length - 1);
    }

    if(newVal.length == 0) {
      newVal = '';
    }
    else  {
      newVal = newVal;
    }
    // set the new value
    this.model.valueAccessor.writeValue(newVal);
    this.rawChange.emit(rawValue)
  }

推荐答案

关于输入更改,请使用以下

on input change use the following

// remove dot and comma's, 123,456.78 -> 12345678
var strVal = myVal.replace(/\.,/g,'');
// change string to integer
var intVal = parseInt(strVal); 
// divide by 100 to get 0.05 when pressing 5 
var decVal = intVal / 100;
// format value to en-US locale
var newVal = decVal.toLocaleString('en-US', { minimumFractionDigits: 2 });

// or in singel line
var newVal = (parseInt(myVal.replace(/\.,/g, '')) / 100).toLocaleString('en-US', { minimumFractionDigits: 2 });

仅使用货币管道将货币管道格式化为USD格式

use currency pipe to format to USD format by using only

var newVal = (parseInt(myVal.replace(/\.,/g, '')) / 100)

希望这会有所帮助.

这篇关于格式化货币输入的角度2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆