How do I round up a value from 39.54 to 39

Asked

Viewed 6,757 times

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?

3 answers

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);

Example

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'

Example


If you use regular expressions you can make the code smaller and use it like this:

function limparClasse(classe) {
    var elementos = document.querySelectorAll('.' + classe);
    for (var i = 0; i < elementos.length; i++) 
        elementos[i].innerHTML = elementos[i].innerHTML.replace(/,.*%/, "%");
}

Example

  • 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!

  • 1

    @lucasinverso, I will adapt the answer

  • Thank you very much.

  • @lucasinverso, I added an example to the answer in case you want to change in several sites.

  • 1

    Thank you Sergio, I was able to adapt, hug.

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

Browser other questions tagged

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