I'm making an app where in fields that accept decimals, the client can put the comma instead of the dot (which is the common visual). What is the best way to transform a "12,34"
string into a numeral like 12.34
?
I'm making an app where in fields that accept decimals, the client can put the comma instead of the dot (which is the common visual). What is the best way to transform a "12,34"
string into a numeral like 12.34
?
You can use 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 want in your code.
Use the following Javascript methods
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 />');
Let's assume that the value formatted in money is: $ 1,234.53
In the example above you will have a semicolon, in this case, if you use .replace(',','.')
, your output number would look like this: 1,234 , but the correct one should be 1234.53 . Think now of thousands ( 1,000,000,000.00 ), how many formatting would you need, then it would be ideal if you had a general rule for everyone, avoiding future upheavals, you can create a following way, 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) : "");
};