0

I have this function to format monetary values:

function formatMonetary(v){   
   v = v.replace(/\D/g,"");
   v = v.replace(/(\d{1})(\d{15})$/,"$1.$2");
   v = v.replace(/(\d{1})(\d{11})$/,"$1.$2");
   v = v.replace(/(\d{1})(\d{8})$/,"$1.$2");
   v = v.replace(/(\d{1})(\d{5})$/,"$1.$2");
   v = v.replace(/(\d{1})(\d{1,2})$/,"$1,$2");
   return v;   
}

When I input just a number 1 or 1,1 this function assume the value:

0,01

0,11

With a value alignment in the right way, is possible this function assume a value in the left way, when I input a number 1 or 1,1 :

1,00

1,10

Sherali Turdiyev
  • 1,745
  • 16
  • 29
Edson Cezar
  • 25,884
  • 5
  • 19
  • 27
  • 1. No need of `{1}` in the regex when you want to select only one digit, you can use `\d` 2. You can chain the `replace` methods – Tushar Sep 29 '15 at 13:57
  • Are you trying to simply add two decimal characters to all numbers? – Daniel Apt Sep 29 '15 at 13:57
  • Yes Daniel, if I input 1, I want 1,00, if I input 1,1 I want 1,10 – Edson Cezar Sep 29 '15 at 13:59
  • "*With a value alignment in the right way, is possible this function assume a value in the left way*" – what does this mean? – David Thomas Sep 29 '15 at 14:02
  • Thanks David, assuming I use number 9, this function returns 0,09, I want if I use number 9 this function returns 9,00 – Edson Cezar Sep 29 '15 at 14:04
  • Edson, when I use it with a number, e.g. `formatMonetary(9);`, I get a type error. If I use it with a string, `formatMonetary('9');`, I get back `"9"`. – nils Sep 29 '15 at 14:06
  • That is, I wanted this function to complete me decimals 1 = 1.00 2 = 2.00 – Edson Cezar Sep 29 '15 at 14:11
  • Use `.toFixed(2)`. Or even better, consult the most upvoted answer on the duplicate; it has the complete code for the transformation you need. – raina77ow Sep 29 '15 at 14:11

0 Answers0