Advertisement
Guest User

Untitled

a guest
Sep 15th, 2019
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. import { Pipe, PipeTransform } from '@angular/core';
  2.  
  3. const PADDING = "000000";
  4.  
  5. @Pipe({
  6. name: 'myCurrency'
  7. })
  8. export class MyCurrencyPipe implements PipeTransform {
  9.  
  10. private DECIMAL_SEPARATOR_ORIGEM: string;
  11.  
  12.  
  13. private DECIMAL_SEPARATOR: string;
  14. private THOUSANDS_SEPARATOR: string;
  15.  
  16. constructor() {
  17. this.DECIMAL_SEPARATOR_ORIGEM = ".";
  18. // TODO comes from configuration settings
  19. this.DECIMAL_SEPARATOR = ",";
  20. this.THOUSANDS_SEPARATOR = ".";
  21. }
  22.  
  23. transform(value: number | string, fractionSize: number = 2): string {
  24. let [integer, fraction = ""] = (value || "").toString()
  25. .split(this.DECIMAL_SEPARATOR_ORIGEM);
  26.  
  27. if (integer == "")
  28. return "0" + this.DECIMAL_SEPARATOR + "00";
  29.  
  30.  
  31. fraction = fractionSize > 0
  32. ? this.DECIMAL_SEPARATOR + (fraction + PADDING).substring(0, fractionSize)
  33. : "";
  34.  
  35. integer = integer.replace(/\B(?=(\d{3})+(?!\d))/g, this.THOUSANDS_SEPARATOR);
  36.  
  37. return "R$ "+integer + fraction;
  38. }
  39.  
  40. parse(value: string, fractionSize: number = 2): string {
  41. let [integer, fraction = ""] = (value || "").split(this.DECIMAL_SEPARATOR);
  42.  
  43. integer = integer.replace(new RegExp(this.THOUSANDS_SEPARATOR, "g"), "");
  44.  
  45. fraction = parseInt(fraction, 10) > 0 && fractionSize > 0
  46. ? this.DECIMAL_SEPARATOR + (fraction + PADDING).substring(0, fractionSize)
  47. : "";
  48.  
  49. return integer + fraction;
  50. }
  51.  
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement