5
How to round the value from within a class in the case 39,54 % OFF for 39 % OFF, values are generated by the system?
5
How to round the value from within a class in the case 39,54 % OFF for 39 % OFF, values are generated by the system?
10
Assuming you have a string with the number inside you can use it like this:
(I took several steps just to be clear)
var string = '39,54 % OFF';
var novaString = string.split('%'); // aqui fica com uma duas partes: ["39,24 ", " OFF"]
var arredondamento = parseInt(novaString[0], 10); // aqui converte a primeira parte para numero inteiro, arredondando-o para baixo
var resultado = arredondamento + '%' + novaString[1]; // aqui junta as duas partes novamente
alert(resultado);
In case you have the number in a variable (which does not seem to have a comma) you can use the Math.floor()
.
If you are changing text in DOM, here is a concrete example using the above code in a function that takes all elements and changes the text:
function limparClasse(classe) {
var elementos = document.querySelectorAll('.' + classe);
for (var i = 0; i < elementos.length; i++) {
var elemento = elementos[i];
var string = elemento.innerHTML;
var novaString = string.split('%');
var arredondamento = parseInt(novaString[0], 10);
var resultado = arredondamento + '%' + novaString[1];
elemento.innerHTML = resultado;
}
}
limparClasse('vtex-cpShow'); // correr a função procurando a classe 'vtex-cpShow'
function limparClasse(classe) {
var elementos = document.querySelectorAll('.' + classe);
for (var i = 0; i < elementos.length; i++)
elementos[i].innerHTML = elementos[i].innerHTML.replace(/,.*%/, "%");
}
3
information about the types of data you are dealing with is missing, but let’s see what we can do:
If its numeric value is of type Float only one parseInt(39.54)
must solve.
If it is a string, "39,54 % OFF"
, something like
"39,54 % OFF".replace(/,[^%]+/, "")
will solve your problem.
Regular expression looks for a comma followed by 1 or more characters other than '%' and replaces with an empty string.
2
Just truncate the value:
function trunc (n) {
return ~~n;
}
Source: https://stackoverflow.com/questions/2125715/javascript-trunc-function
Browser other questions tagged javascript
You are not signed in. Login or sign up in order to post.
Sergio, it would be exactly that, But in case you would need to take the value of a class ex: <span class="vtex-cpSave vtex-cpShow discount ">15,0 % OFF</span> would not be of a fixed value, sorry for the lack of knowledge rs. Thank you!
– lucas inverso
@lucasinverso, I will adapt the answer
– Sergio
Thank you very much.
– lucas inverso
@lucasinverso, I added an example to the answer in case you want to change in several sites.
– Sergio
Thank you Sergio, I was able to adapt, hug.
– lucas inverso