我想将输入的字符串分隔为印度货币格式,就像我输入123456表示一样,那么我想得到 1,23,456

I want to seperate the entered string as indian money format like if i entered 123456 means, then i want to get 1,23,456

本文关键字:输入 一样 想得到 表示 字符串 分隔 格式 货币 123456      更新时间:2023-09-26

我想将输入的字符串分隔为印度货币格式,就像我输入123456表示一样,那么我想得到 1,23,456:

我使用的代码是:

function addCommas(x)
{
var parts=x.toString().split(".");
parts[0]=parts[0].replace(/'B(?=('d{3})+(?!'d))/g, ",");
return parts.join(".");`enter code here
}

它给出的答案是 123,456。

我希望输出为 1,23,456

正则表达式解决方案将使用积极的前瞻(?=pattern)来确保序列位于字符串的正确部分

您需要匹配 1 或 2 个'd(数字),其中

  • 后跟零组或多组 2 位数字(?:'d{2})*
  • 后跟一组 3 位数字和字符串的末尾'd{3}$

所以你会在这个/('d'd?)(?=(?:'d{2})*'d{3}$)/编写一个正则表达式,并在使用

'1234567890'.replace(/('d'd?)(?=(?:'d{2})*'d{3}$)/g, '$1,');
// "1,23,45,67,890"

你可以看看这个

var formattedCurrencyFunc = function(){
  function currencyFormat(num) {
    return num.toFixed(0).replace(/('d)(?=('d{3})+(?!'d))/g, "$1,")
  }
    $(".formattedCurrency").each(function () {
      var $currSpan = $(this).text(),
      $currFormatted = currencyFormat(parseFloat($currSpan));
      $(this).removeClass('formattedCurrency');
      $(this).html($currFormatted);
    });
}

formattedCurrencyFunc()

代码笔的完整工作演示

http://codepen.io/harishgadiya/pen/pgZpXN