【问题标题】:how to compare two currency in jquery with comma如何用逗号比较jquery中的两种货币
【发布时间】:2019-02-20 01:52:29
【问题描述】:

我有两个输入,当我开始输入数字时,它会自动更改为货币,如下所示:

1,000
10,000
100,000
1,000,000

那么你如何比较这两个输入?
因为是逗号,所以会产生比较问题。

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;
    }
}

【问题讨论】:

  • 用空字符串替换所有逗号,然后比较
  • 请分享html
  • 为什么要将一个 jQuery 对象包装在另一个 jQuery 对象中? $($("#price_meter))$("#price_meter") 相同...此外,您共享的代码将逗号替换为空字符串,因此应该可以进行比较。请提供一个minimal reproducible example 来说明问题。

标签: javascript jquery compare currency


【解决方案1】:

这里有一些方法可以做到这一点。我将您发布的示例放在一个数组中,以避免多出 4 个变量。

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】:

    你可以参考下面的代码行

    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(''));

      我假设您希望它最后是一个数字,以便与其他数字进行比较。如果你想保留一个字符串let newString = numberString.split(",").join('');

      【讨论】:

        猜你喜欢
        • 2022-01-22
        • 2019-07-11
        • 1970-01-01
        • 2012-07-26
        • 1970-01-01
        • 2018-03-29
        • 2012-03-07
        • 1970-01-01
        • 2014-09-07
        相关资源
        最近更新 更多