how to compare two currency in jquery with comma

百般思念 提交于 2021-01-29 10:54:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!