1
Good afternoon, I have the function below javascript to carry out the account when leaving the discount field:
function calcular1() {
String.prototype.formatMoney = function() {
var v = this;
if (v.indexOf('.') === -1) {
v = v.replace(/([\d]+)/, "$1,00");
}
v = v.replace(/([\d]+)\.([\d]{1})$/, "$1,$20");
v = v.replace(/([\d]+)\.([\d]{2})$/, "$1,$2");
v = v.replace(/([\d]+)([\d]{3}),([\d]{2})$/, "$1.$2,$3");
return v;
};
var v1 = document.getElementById("txtValoraPagar").value;
var v2 = document.getElementById("txtDesconto").value;
var txtTotalPagar = document.getElementById("txtTotalPagar");
if ((v2.replace("R$", "").replace(",", ".").replace(/\s*/g, '')) > (v1.replace(",", ".").replace(/\s*/g, ''))) {
alert('Valor do desconto não pode ser maior do que o valor a receber.');
document.getElementById("txtDesconto").value = '';
return false;
}
if ((v1 != "") && (v2 != "") && (v1.replace(",", ".").replace(/\s*/g, '') >= v2.replace("R$", "").replace(",", ".").replace(/\s*/g, ''))) {
txtTotalPagar.value = (eval(v1.replace(",", ".") - eval(v2.replace("R$", "").replace(",", "."))));
txtTotalPagar.value = 'R$ ' + String(txtTotalPagar.value).formatMoney();
}
For example, if the value is 15.00 and the discount is 5.00 it enters as if the discount was greater than the value, and informs Alert. Now if the value is 15.00 and I put the discount of 1.00, it works, and shows the total amount to pay right, of 14.00. By what to understand, he is counting the first number of the 15, q is 1, and takes the 5. I do not know why this is happening.
The result as you are describing is correct because you are comparing instances of characters and not numbers.
– Pagotti