Insert a dot in the penultimate variable item

Asked

Viewed 215 times

1

I have a variable with the value "14013" and I’m trying to insert a point to have the following value "140.13" in my loop.

for (var i in teste) {
  for (var j in (teste2[teste[i]])) {
       valorFinal[j] = resultado1 + resultado2;
       //valorFinal[j] precisa ter um ponto antes do penultimo item 
  }
}

2 answers

2

Try this, I created a function insertDot(), which takes as argument the number you want:

var a = 14013;

function insertDot(a){
  a = a.toString(); // Transforma em String 
  var beforeDot = a.substring(0, a.length-2); // Captura do primeiro ao penúltimo caractere
  var afterDot = a.substring(a.length-2, a.length); // Captura o penúltimo ao último caractere
  return parseFloat(beforeDot + "." + afterDot); // retorna um NÚMERO com com o ponto inserido
}

document.body.innerHTML += insertDot(a);
document.body.innerHTML += "<br>";
document.body.innerHTML += insertDot(a) * 2;

So just do:

function insertDot(a){
  a = a.toString();
  return parseFloat(a.substring(0, a.length-2)+"."+a.substring(a.length-2, a.length));
}
for (var i in teste) {
  for (var j in (teste2[teste[i]])) {
       valorFinal[j] = resultado1 + resultado2;
       valorFinal[j] = insertDot(valorFinal[j]);
  }
}

With a second argument that gets the point position, as suggested by Sergio:

var a = 14013;

function insertDot(a, pos){
  a = a.toString(); 
  if(pos > 0){
     a = parseFloat(a.substring(0, pos) + "." + a.substring(pos, a.length));
  }else{
     a = parseFloat(a.substring(0, a.length+pos) + "." + a.substring(a.length+pos, a.length));
  }
  return a;
}

document.body.innerHTML += insertDot(a, 1);
document.body.innerHTML += "<br>";
document.body.innerHTML += insertDot(a, -2);
document.body.innerHTML += "<br>";
document.body.innerHTML += insertDot(a, -2) * 2;

  • 2

    I liked it if I had a second argument with the point position, like inserDot(192, -1) then it was very flexible. But it seems that the AP is already satisfied with the other answer.

  • 2

    @Sergio, I edited the answer only at the level of subsequent uses by other users. Thank you for the suggestion.

  • Thank you so much for the personal help, tested and also helped me!

1


for (i in teste) {
    for (j in (teste2[teste[i]])) {
        valorFinal[j] = (resultado1 + resultado2);
        var res = valorFinal[j].toString();
        var dec = Math.floor(res.length - 2);
        var resp = res.substring(0, dec) + "." + res.substring(dec);
    }
}

I think that solves.

  • I edited the answer. .

  • Now it worked @Vitor, thank you so much for your help friend!

  • Why var dec = Math.floor(res.length - 2);?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.