Function to search in a chain the commas and replace them by point


I want to make a function that when you pass it for example this amount 20000,01 it returns me 20000.01

function cambiarDecimales(monto)
	var montoEnv;
	montoEnv =  new Intl.NumberFormat(["en-US"],{maximumFractionDigits:2}).format(monto);

	if(contry == 'v' || contry == 'c') {
		montoEnv = montoEnv.replace(/\./g, 'p')
		montoEnv = montoEnv.replace(/\,/g, '.');
		montoEnv = montoEnv.replace(/\p/g, ',');

	return montoEnv;
asked by javier 28.12.2018 в 20:16

1 answer


It's not that difficult, although as mentioned above there are bookstores that do the work, but I'll leave you an example of how to do it. Maybe you should make an example that is more developed so that there are not incomplete things for the next time .. but going from it:

If what you want is a function that you can use every time you need to change an amount, you have to pass the necessary arguments, such as the amount in text string, the country (I get this from a dropdown) and in the example I change the value of an html paragraph so I pass a parameter to identify the id of this in the function.

As you can see inside I only have to condition that if the country is x, in the value of the string the characters specified in the Regex will be replaced using the replace() method, then I just have to give the function the arguments that requires when executing with x method.

In the following example as I mentioned above, I'm changing the value of my html within the function itself, but to get the value of in this case cadena we just return it in the function and doing console.log() of this We can see that it gives us the desired result in the form of a chain.



function evalCountry(cadena, pais, id) {
  var result;
  if (pais == "c"){
    cadena = cadena.replace(/\,/g,".");
    document.getElementById(id).innerHTML = cadena;
    result = cadena;
  }else if(pais == "p" ){
    cadena = cadena.replace(/\./g,",");
    document.getElementById(id).innerHTML = cadena;
    result = cadena;
  return result;

document.querySelector("#btn").addEventListener("click", function(){
  var e = document.getElementById("h");
  var country = e.options[e.selectedIndex].value;
  var montoEnv = "27644154,00"
  var target = "p";
  console.log(evalCountry(montoEnv, country, target));
<p id="p">27644154,00</p>
<select id="h" name="country">
  <option value="p">Coma</option>
  <option value="c">Punto</option>
<button id="btn">convertir</button>

I hope you find it helpful, greetings.

answered by 28.12.2018 в 22:19