Transform the value into String to Integer

-2

I need to handle this error:

  

"Can not deserialize value of type java.lang.Integer

     

from String "$ 5,000.00": not a valid Integer value ".

I need to convert the string parameter ($ 5,000) to integer (5000).

Treatment I started:

var valorAplicacao = vm.valor.replace('R$ ', '').split(".").join("").replace(',', '.');
valorAplicacao = parseFloat(valorAplicacao);    
    
asked by anonymous 09.11.2018 / 14:33

3 answers

0

Your code is almost right, but let's think about what we should do:

  • Remove the "R $";
  • Remove the ".";
  • Replace the comma with ".";
  • Convert to integer;

In that order, it would look like this:

var numString="R$ 5.000,00";
var numInteiro = parseInt(numString.replace('R$', '').replace('.','').replace(',', '.'));

console.log(numInteiro);
    
09.11.2018 / 14:48
0

Your monetary value has decimal places, but you explicitly said that you want to convert to integer, so my suggestion ignores the decimal places of your String:

var numString  = "R$ 5.000,00";
var numInteiro = numString.replace(/[^\d,]/g, '').split(',')[0];

console.log(numInteiro); // Saída: 5000
    
09.11.2018 / 15:15
-1

Using regex to remove characters that are not numbers, this can help you:

In this conversion you will have the value including the decimal places:

valorAplicacao = parseFloat(valorAplicacao.replace(',','.').replace(/[^\d.-]/g, ''));

If you need only integers you can use rounding:

var intvalue = Math.floor(valorAplicacao);
var intvalue = Math.ceil(valorAplicacao); 
var intvalue = Math.round(valorAplicacao);

Reference:

09.11.2018 / 14:38