Convert a string in monetary format to number and subtract 90%

Asked

Viewed 170 times

1

How can I convert a string to number and subtract 90%?

I tried to make a code (below), but it returns the value 3205.5 and I’m not getting to know why. If I use the value R$ 320,50 works.

var a = 'R$ 320,55';

function getMoney (str) {
    return parseInt( str.replace(/[\D]+/g,'') );
}

function formatReal (int) {
  var tmp = int+'';
  tmp = tmp.replace(/([0-9]{2})$/g, ",$1");
  if( tmp.length > 6 )
    tmp = tmp.replace(/([0-9]{3}),([0-9]{2}$)/g, ".$1,$2");

  return tmp;
}

var b = getMoney (a);
var c = b - (b *0.9); 
console.log( formatReal( c ) );

  • This has more mathematical problem face than programming itself...

  • hi @Marceloboni ... really. But take a look at what’s happening... updated the post.

  • 1

    For the record, the regex could be /\D+/g - the brackets are unnecessary in this case.

2 answers

3


The problem lies in its function getMoney, that is not converting the numeric string (in Brazilian format) correctly.

More specifically, the error is due to this regular expression:

/[\D]+/g

She will give match in whole character that is not numeric. This means that you will also remove the decimal separator from the number (,), which is basically the same thing as multiplying it by 100. Of course, this is not what we want.

To solve, just correct the regular expression.

/[^\d,]+/g

Note that now any character that is not numerical or a comma (which is our decimal separator) will be removed. Then we need to change the comma (, - which is the decimal separator of the Brazilian currency) for the point (. - which is the decimal separator that Javascript understands when doing parseFloat).

We’ll keep:

function getMoney(str) {
  return str
    .replace(/[^\d,]+/g, '') // Remove caracteres desnecessários.
    .replace(',', '.');      // Troca o separador decimal (`,` -> `.`)
}

console.log(getMoney('R$ 123.456,89')); // 123456.89

Now we can calculate the subtraction of the percentage satisfactorily:

function getMoney(str) {
  return str.replace(/[^\d,]+/g, '') 
    .replace(',', '.');
}

const a = 'R$ 320,55';
const b = getMoney(a);
const c = b - b * 0.9;

console.log(c);

// Formatando para o formato de moeda brasileira:
const formatter = new Intl.NumberFormat('pt-BR', {
  style: 'currency',
  currency: 'BRL'
});
const d = formatter.format(c);
console.log(d); // R$ 32,06

As you can see, it is also not necessary to implement a function like formatReal at hand, since Javascript already has monetary formatting Apis included, such as Intl.NumberFormat or Number.prototype.toLocaleString.

  • 2

    Could also use the original regex and divide by 100 :-)

  • 1

    @hkotsubo really hadn’t even thought about it! : D Good idea.

  • Thank you very much for the clarifications... especially in the question of regular expression !

2

You are having problems at the time of formatting (turn the string to float and then to string again to perform the operation)

var a = 'R$ 320,55';
/**
* Transforma a string em um float
*/
function getMoney (str)
{
    var valor= str.replace(/[^\d,]/g,''); //remove todos os caracteres menos numeros e virgula
    valor = valor.replace(',','.'); //troca virgula por ponto
    return parseFloat(valor);
}
/**
* Transforma o float de volta pra string com formatação em reais
*/
function formatReal (valor)
{
    return valor.toLocaleString('pt-BR', {style: 'currency', currency: 'BRL'})
}
  var b = getMoney (a);
  var c = b - (b *0.9); 
  console.log(formatReal(c));

Take a look at toLocaleString

  • 1

    hi @Vitor .... Ball show. Clear the explanation. Thank you very much... with toLocaleString everything gets simpler,

Browser other questions tagged

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