问题
I have two inputs that when I start typing number, it automatically changes to currency, like this:
1,000
10,000
100,000
1,000,000
so how do you compare these two inputs?
Because it is a comma, it creates a comparative problem.
function priceCompare() {
var price_meterVal;
var priceVal;
$("#price_meter").on("keyup",function () {
price_meterVal = $($("#price_meter")).val().replace(/,/g, '');
});
$("#price").on("keyup",function () {
priceVal = $($("#price")).val().replace(/,/g, '');
});
if (priceVal <= price_meterVal){
$("#priceError").html('قیمت کل ملک نمی تواند کمتر از قیمت متری باشد.');
contractStatus = false;
}else {
contractStatus = true;
}
}
回答1:
Here are a few ways to do it. I put the examples you posted in an array to avoid having 4 more variables.
const sampleInputs = [ '1,000', '10,000', '100,000', '1,000,000' ]
// + is a shortcut to convert to a number
// split at commas
const splitMethod = +sampleInputs[0].split(',').join('')
// match digits
const regexOne = +(sampleInputs[1].match(/\d/g) || []).join('')
// replace commas
const regexTwo = +sampleInputs[2].replace(/,/g, '')
// filter
const fi = +sampleInputs[3]
.split('')
.filter(n => n !== ',')
.join('')
console.log('splitMethod', splitMethod)
console.log('regexOne', regexOne)
console.log('regexTwo', regexTwo)
console.log('filter', fi)
回答2:
you can refer below line of code
function comparecurrent(cur1, cur2) {
if (parseInt(cur1.replace(/,/g, '')) > parseInt(cur2.replace(/,/g, ''))) {
alert("currency 1");
}
else if (parseInt(cur1.replace(/,/g, '')) < parseInt(cur2.replace(/,/g, '')))
{
alert("currency 2");
}
else {
alert('equal');
}
}
回答3:
let newInteger = parseInt(numberString.split(",").join(''));
I'm assuming you want it to be a number at the end to compare to other numbers. If you'd like to keep it a string let newString = numberString.split(",").join('');
来源:https://stackoverflow.com/questions/52345714/how-to-compare-two-currency-in-jquery-with-comma