How to make Javascript calculations accepting comma to separate decimal places

Asked

Viewed 23,670 times

10

I’m making an app where in fields that accept decimals, the customer can put the comma instead of the dot (which is the common one visually). What is the best way for me to transform a string "12,34" in a numeral as 12.34?

  • You think about changing the JS core?

  • Did you see this question and the answers? -> http://answall.com/q/11018/129

5 answers

12

Use the following Javascript methods

  • replace to exchange the comma for a point
  • parseFloat to convert to float/double
  • toFixed to define how many decimal places you want after the comma

var string1 = '21,21';
var string2 = '10,8';

var numero1 = parseFloat(string1.replace(',', '.'));
var numero2 = parseFloat(string2.replace(',', '.'));

document.write('Número 1: <b>' + numero1 + '</b><br />');
document.write('Número 2: <b>' + numero2 + '</b><br />');
document.write('Soma: <b>' + (numero1 + numero2).toFixed(2) + '</b><br />');

  • vlw but had already been answered earlier

  • 7

    @Leandroluk the first answer was mine, but alright, the important thing is to solve your problem. :)

8

You can use the replace where you delimit the character to be replaced and then pass it to float:

var comVigula = "1,87";
comVirgula = parseFloat(comVirgula.replace(',','.'));
alert(comVirgula);

After this just use as you wish in your code.

6


Let’s assume that the amount formatted in cash is: R$ 1.234,53

In the example above you will have semicolon, in this case, if you use the .replace(',','.'), your outgoing number would be something like this: 1.234, but the right thing should be 1234.53. Think now of the thousands (1,000,000,000.00), how many formatting would need..., so it would be ideal to have a general rule for everyone, avoiding future inconvenience, you can create a method as follows, regardless of the input value:

//em float
formatNumber(1234.53);
//em string real
formatNumber('1.234,53');
//em string real sem ponto
formatNumber('1234,53');
//em string americano
formatNumber('1,234.53');

//retornará 1234.53
function formatNumber(value) {
    value = convertToFloatNumber(value);
    return value.formatMoney(2, '.', '');
}
//retornará 1.234,53
function formatNumber(value) {
    value = convertToFloatNumber(value);
    return value.formatMoney(2, ',', '.');
}
//retornará 1,234.53
function formatNumber(value) {
    value = convertToFloatNumber(value);
    return value.formatMoney(2, '.', ',');
}

 //transforma a entrada em número float
 var convertToFloatNumber = function(value) {
     value = value.toString();
      if (value.indexOf('.') !== -1 && value.indexOf(',') !== -1) {
          if (value.indexOf('.') <  value.indexOf(',')) {
             //inglês
             return parseFloat(value.replace(/,/gi,''));
          } else {
            //português
             return parseFloat(value.replace(/./gi,'').replace(/,/gi,'.'));
          }      
      } else {
         return parseFloat(value);
      }
   }

//prototype para formatar a saída  
Number.prototype.formatMoney = function (c, d, t) {
    var n = this,
        c = isNaN(c = Math.abs(c)) ? 2 : c,
        d = d == undefined ? "." : d,
        t = t == undefined ? "," : t,
        s = n < 0 ? "-" : "",
        i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "",
        j = (j = i.length) > 3 ? j % 3 : 0;
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};

1

I suppose you want to do some calculations with the numbers your customers put in and also think you might want to save some values in your database. Then it would be good if it were standardized and everywhere you saved the same number (e.g. 123123 instead of 123,123,123) and only when you went to show your client would you put the commas and stitches they needed.

This way, you can use the functions both in the database and in your backend as well as in your front end and clarity only need to change something when you show it to your creator.

If you want to put stitches and commas too, for example 123.232,32 I use the following function: (It is worth remembering that it was made for product prices, if you really want to just exchange commas for points and points for commas it is better to use in a.replace(',', '.'))

function brl_comma_dot(num){
    var num_1 = parseInt(num);//Pega a parte inteira do numero
    var num_2 = Math.round((num-num_1)*100);//Pega a parte nao inteira
    var digits = [];
    while(num_1 >= 1){//Enquanto a parte inteira for maior que 1
        var digit = num_1 % 10;
        digits.push(digit);//Guarda cada digito neste array em ordem contraria
        num_1 = Math.floor(num_1/10);
    }
    num_1 ="";
    //Para todos os numeros no array adiciona "." a cada 3 numeros
    for(var i = 0; i< digits.length; i++){a 
        if( i % 3 == 0 && i != 0){
            var comma = '.';
        }else{
            var comma = '';
        }
        num_1 = digits[i]+ comma +num_1;
    }

    if(num_2 < 10 && num_2 != 0){
        num_2 = "0" + num_2;
    }else if(num_2 == 0){
        num_2 = "00";
    }else if(num_2 % 10 == 0 && num_2 !=0){
        num_2 = num_2/10;
        num_2 = num_2+"0";
    }
    if(num_1 == 0){
        num_1 = "0";
    }
    var num_with_comma = num_1+","+num_2;
    return num_with_comma;
}

1

Just complementing Ivan Ferrer’s answer on the line:

            //português
         return parseFloat(value.replace(/./gi,'').replace(/,/gi,'.'));

It was missing the " ." to escape the ".". Adjusting would look like this:

            //português
         return parseFloat(value.replace(/\./gi,'').replace(/,/gi,'.'));

With fit, it worked perfect for me.

Browser other questions tagged

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