convert.dec.pipe.ts 977 B

1234567891011121314151617181920212223242526272829303132333435
  1. import { Pipe, PipeTransform } from '@angular/core';
  2. @Pipe({
  3. name: 'numberPipe'
  4. })
  5. export class NumberPipePipe implements PipeTransform {
  6. transform(val) {
  7. if(val){
  8. val = this.format_number(val.toString(), '');
  9. }
  10. return val;
  11. }
  12. format_number(number, prefix) {
  13. let thousand_separator = ',',
  14. decimal_separator = '.',
  15. regex = new RegExp('[^' + decimal_separator + '\\d]', 'g'),
  16. number_string = number.replace(regex, '').toString(),
  17. split = number_string.split(decimal_separator),
  18. rest = split[0].length % 3,
  19. result = split[0].substr(0, rest),
  20. thousands = split[0].substr(rest).match(/\d{3}/g);
  21. if (thousands) {
  22. let separator = rest ? thousand_separator : '';
  23. result += separator + thousands.join(thousand_separator);
  24. }
  25. result = split[1] != undefined ? result + decimal_separator + split[1] : result;
  26. return prefix == undefined ? result : (result ? prefix + result : '');
  27. };
  28. }