How do I round off a value from 39.54 to 39

2

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?

    
asked by anonymous 23.04.2014 / 17:03

3 answers

7

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

Example

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'

Example

If you use regular expressions you can make the code smaller and use 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

    
23.04.2014 / 17:09
3

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.

    
23.04.2014 / 17:14
2

Just truncate the value:

 function trunc (n) {
    return ~~n;
 }

Source: link

    
23.04.2014 / 17:10