How to round the value from within a class, in the case of 39.54% OFF to 39% OFF Are the values generated by the system?
How to round the value from within a class, in the case of 39.54% OFF to 39% OFF Are the values generated by the system?
Assuming you have a string with the number in there you can use this:
(I took several steps just to be clearer)
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);
If you have the number in a variable (which does not seem to have a comma), you can use Math.floor()
.
If you are changing text in the DOM, here is a concrete example using the above code in a function that takes all the 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(/,.*%/, "%");
}
missing information on the types of data you are dealing with, but let's see what we can do:
If your numeric value is of type Float only a parseInt(39.54)
must resolve.
If it is a string, "39,54 % OFF"
, something like
"39,54 % OFF".replace(/,[^%]+/, "")
will solve your problem.
The regular expression looks for a comma followed by 1 or more characters other than '%' and replaces it with an empty string.