Format string or float for currency

Asked

Viewed 5,506 times

1

I’ve been doing some research but I couldn’t find a solution. I have a float for example: 2087500, I want to leave it as follows $20,875.00.

I found several methods of passing float to currency but all have a point (.) before the last two digits to be able to work, like this 20875.00. I tried to use replace(/([0-9]{2})$/g, ". $1") to put this point but it is only added in String. And as I said, the functions I found work only with float.

Could someone help me with a functional solution please.

  • 1

    The last 2 numbers are decimal?

3 answers

3


It would be better to use function Intl.Numberformat of the object Intl, it facilitates formatting numbers according to language, example:

//Instanciando o objeto
var formatter = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
  minimumFractionDigits: 2,
});
//pega o valor no campo e transforma em float
var valor = parseFloat(document.getElementById("moeda").value);
/*FORMATA CONFORME CONFIGURAÇÕES DEFINIDAS NO formatter*/
var formatado = formatter.format(valor); 
//Coloca o valor formatado no campo resultado
document.getElementById("resultado").value = formatado;
<input type="text" id="moeda" value="20875.00">
<input type="text" id="resultado" value="">

//Instanciando o objeto
var formatter = new Intl.NumberFormat('pt-BR', {
  style: 'currency',
  currency: 'BRL',
  minimumFractionDigits: 2,
});
//pega o valor no campo e transforma em float
var valor = parseFloat(document.getElementById("moeda").value);
/*FORMATA CONFORME CONFIGURAÇÕES DEFINIDAS NO formatter*/
var formatado = formatter.format(valor); 
//Coloca o valor formatado no campo resultado
document.getElementById("resultado").value = formatado;
<input type="text" id="moeda" value="20875.00">
<input type="text" id="resultado" value="">

OBS: To use this way, both the string as to the float that you want to format should contain the correct value with decimal places, for example:

1 = $1.00
1.0 = $1.00
10 = $10.00

2

Functions with and without input.

var mask = {
   money: function() {
      var el = this
      ,exec = function(v) {
         v = v.replace(/\D/g,"");
         v = new String(Number(v));
         var len = v.length;
         if (1== len)
            v = v.replace(/(\d)/,"0,0$1");
         else if (2 == len)
            v = v.replace(/(\d)/,"0,$1");
         else if (len > 2) {
            v = v.replace(/(\d{2})$/,',$1');
            if (len > 5) {
               var x = len - 5
               ,er = new RegExp('(\\d{'+x+'})(\\d)');
               v = v.replace(er,'$1.$2');
            }
         }
         return v;
      };
      setTimeout(function(){
         el.value = exec(el.value);
      },1);
   }
}

$(function(){
   $('input').bind('keypress',mask.money)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text"  value=""/>

function mascara(v) {
  v = v.replace(/\D/g,"");
  v = new String(Number(v));
  var len = v.length;
  if (1== len)
    v = v.replace(/(\d)/,"0,0$1");
  else if (2 == len)
    v = v.replace(/(\d)/,"0,$1");
  else if (len > 2) {
    v = v.replace(/(\d{2})$/,',$1');
  if (len > 5) {
  var x = len - 5
  ,er = new RegExp('(\\d{'+x+'})(\\d)');
  v = v.replace(er,'$1.$2');
  }
}
return v;
}
console.log(mascara('2087500'))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

  • In case I already have the value in a variable, I would need to apply the mask and $("#boxValorTotal4"). text(valueComscara); how could I apply it? That without clicking or anything like that, when the page loads it already does it.

  • I changed the function to pass only one value and she put the mask.

  • It worked, but if it is necessary to apply the mask in numbers above 1 million it no longer scores correctly. Ex: 20800.075,00

  • Really, I asked exactly to your question kk, has as you go modifying according to your needs in houses.

  • Tendi, took a look here and dropped the rsrs, obg same

1

just dividing by 100 would not be enough?

var intl = new Intl.NumberFormat("en-US", { 
  style: "currency", 
  currency: "USD"
});
var valor = 2087500;
var moeda = intl.format((valor / 100));
console.log(valor, moeda);

Browser other questions tagged

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