【问题标题】:Jquery price format with lakhs separator?带有十万分隔符的Jquery价格格式?
【发布时间】:2013-07-18 17:05:36
【问题描述】:

我得到了 Jquery Price Format jQuery Plugin,它与千位分隔符配合得很好(例如:32'32,232.33),但我需要千位分隔符,也像 (32'32,232.33) 一样,我已经更改了 Jquery 但它似乎只有十万人在工作,而不是在成千上万的人工作

格式.js

/*

* Price Format jQuery Plugin
* Created By Eduardo Cuducos cuducos [at] gmail [dot] com
* Currently maintained by Flavio Silveira flavio [at] gmail [dot] com
* Version: 1.7
* Release: 2012-02-22

* original char limit by Flavio Silveira <http://flaviosilveira.com>
* original keydown event attachment by Kaihua Qi
* keydown fixes by Thasmo <http://thasmo.com>
* Clear Prefix on Blur suggest by Ricardo Mendes from PhonoWay
* original allow negative by Cagdas Ucar <http://carsinia.com>
* keypad fixes by Carlos Vinicius <http://www.kvinicius.com.br> and Rayron Victor
* original Suffix by Marlon Pires Junior
* CentsLimit set to zero fixed by Jereon de Jong
* original idea for the use of the plus sign

*/

(function($) {

    /****************
    * Main Function *
    *****************/
    $.fn.priceFormat = function(options)
    {

        var defaults =
        {
            prefix: 'US$ ',
            suffix: '',
            centsSeparator: '.',
            thousandsSeparator: ',',
           lakhsSeparator: "'",
            limit: false,
            centsLimit: 2,
            clearPrefix: false,
            clearSufix: false,
            allowNegative: false,
            insertPlusSign: false
        };

        var options = $.extend(defaults, options);

        return this.each(function()
        {

            // pre defined options
            var obj = $(this);
            var is_number = /[0-9]/;

            // load the pluggings settings
            var prefix = options.prefix;
            var suffix = options.suffix;
            var centsSeparator = options.centsSeparator;
            var thousandsSeparator = options.thousandsSeparator;
            var lakhsSeparator = options.lakhsSeparator;
            var limit = options.limit;
            var centsLimit = options.centsLimit;
            var clearPrefix = options.clearPrefix;
            var clearSuffix = options.clearSuffix;
            var allowNegative = options.allowNegative;
            var insertPlusSign = options.insertPlusSign;

            // If insertPlusSign is on, it automatic turns on allowNegative, to work with Signs
            if (insertPlusSign) allowNegative = true;

            // skip everything that isn't a number
            // and also skip the left zeroes
            function to_numbers (str)
            {
                var formatted = '';
                for (var i=0;i<(str.length);i++)
                {
                    char_ = str.charAt(i);
                    if (formatted.length==0 && char_==0) char_ = false;

                    if (char_ && char_.match(is_number))
                    {
                        if (limit)
                        {
                            if (formatted.length < limit) formatted = formatted+char_;
                        }
                        else
                        {
                            formatted = formatted+char_;
                        }
                    }
                }

                return formatted;
            }

            // format to fill with zeros to complete cents chars
            function fill_with_zeroes (str)
            {
                while (str.length<(centsLimit+1)) str = '0'+str;
                return str;
            }

            // format as price
            function price_format (str)
            {
                // formatting settings
                var formatted = fill_with_zeroes(to_numbers(str));
                var thousandsFormatted = '';
                var thousandsCount = 0;
                var lakhsFormatted = '';
                var lakhsCount = 0;
                // Checking CentsLimit
                if(centsLimit == 0)
                {
                    centsSeparator = "";
                    centsVal = "";
                }

                // split integer from cents
                var centsVal = formatted.substr(formatted.length-centsLimit,centsLimit);
                var integerVal = formatted.substr(0,formatted.length-centsLimit);

                // apply cents pontuation
                formatted = (centsLimit==0) ? integerVal : integerVal+centsSeparator+centsVal;

                // apply thousands pontuation


                if (thousandsSeparator || $.trim(thousandsSeparator) != "")
                {
                    for (var j=integerVal.length;j>0;j--)
                    {
                        char_ = integerVal.substr(j-1,1);
                        thousandsCount++;
                        if (thousandsCount%3==0) char_ = thousandsSeparator+char_;
                        thousandsFormatted = char_+thousandsFormatted;
                    }

                    //
                    if (thousandsFormatted.substr(0,1)==thousandsSeparator) thousandsFormatted = thousandsFormatted.substring(1,thousandsFormatted.length);
                    formatted = (centsLimit==0) ? thousandsFormatted : thousandsFormatted+centsSeparator+centsVal;
                }

                // apply lakhs pontuation
             if (lakhsSeparator || $.trim(lakhsSeparator) != "")
                {

                    for (var j=integerVal.length;j>0;j--)
                    {
                        char_ = integerVal.substr(j-1,1);
                        char1_ = integerVal.substr(j-1,1);
                        lakhsCount++;





                        if (lakhsCount%5==0)
                     char_ =lakhsSeparator+char_;
                        lakhsFormatted = char_+lakhsFormatted;


                    }


                    if (lakhsFormatted.substr(0,1)==lakhsSeparator) lakhsFormatted = lakhsFormatted.substring(1,lakhsFormatted.length);
                    formatted = (centsLimit==0) ? lakhsFormatted : lakhsFormatted+centsSeparator+centsVal;
                }


                // if the string contains a dash, it is negative - add it to the begining (except for zero)
                if (allowNegative && str.indexOf('-') != -1 && (integerVal != 0 || centsVal != 0))
                    formatted = '-' + formatted;
                else if (insertPlusSign && (integerVal != 0 || centsVal != 0))
                    formatted = '+' + formatted;

                // apply the prefix
                if (prefix) formatted = prefix+formatted;

                // apply the suffix
                if (suffix) formatted = formatted+suffix;

                return formatted;
            }

            // filter what user type (only numbers and functional keys)
            function key_check (e)
            {
                var code = (e.keyCode ? e.keyCode : e.which);
                var typed = String.fromCharCode(code);
                var functional = false;
                var str = obj.val();
                var newValue = price_format(str+typed);

                // allow key numbers, 0 to 9
                if((code >= 48 && code <= 57) || (code >= 96 && code <= 105)) functional = true;

                // check Backspace, Tab, Enter, Delete, and left/right arrows
                if (code ==  8) functional = true;
                if (code ==  9) functional = true;
                if (code == 13) functional = true;
                if (code == 46) functional = true;
                if (code == 37) functional = true;
                if (code == 39) functional = true;
                // Minus Sign, Plus Sign
                if (allowNegative && (code == 189 || code == 109)) functional = true; // dash as well
                if (insertPlusSign && (code == 187 || code == 107)) functional = true;

                if (!functional)
                {
                    e.preventDefault();
                    e.stopPropagation();
                    if (str!=newValue) obj.val(newValue);
                }

            }

            // inster formatted price as a value of an input field
            function price_it ()
            {
                var str = obj.val();
                var price = price_format(str);
                if (str != price) obj.val(price);
            }

            // Add prefix on focus
            function add_prefix()
            {
                var val = obj.val();
                obj.val(prefix + val);
            }

            function add_suffix()
            {
                var val = obj.val();
                obj.val(val + suffix);
            }

            // Clear prefix on blur if is set to true
            function clear_prefix()
            {
                if($.trim(prefix) != '' && clearPrefix)
                {
                    var array = obj.val().split(prefix);
                    obj.val(array[1]);
                }
            }

            // Clear suffix on blur if is set to true
            function clear_suffix()
            {
                if($.trim(suffix) != '' && clearSuffix)
                {
                    var array = obj.val().split(suffix);
                    obj.val(array[0]);
                }
            }

            // bind the actions
            $(this).bind('keydown.price_format', key_check);
            $(this).bind('keyup.price_format', price_it);
            $(this).bind('focusout.price_format', price_it);

            // Clear Prefix and Add Prefix
            if(clearPrefix)
            {
                $(this).bind('focusout.price_format', function()
                {
                    clear_prefix();
                });

                $(this).bind('focusin.price_format', function()
                {
                    add_prefix();
                });
            }

            // Clear Suffix and Add Suffix
            if(clearSuffix)
            {
                $(this).bind('focusout.price_format', function()
                {
                    clear_suffix();
                });

                $(this).bind('focusin.price_format', function()
                {
                    add_suffix();
                });
            }

            // If value has content
            if ($(this).val().length>0)
            {
                price_it();
                clear_prefix();
                clear_suffix();
            }

        });

    };

    /**********************
    * Remove price format *
    ***********************/
    $.fn.unpriceFormat = function(){
      return $(this).unbind(".price_format");
    };

    /******************
    * Unmask Function *
    *******************/
    $.fn.unmask = function(){

        var field = $(this).val();
        var result = "";

        for(var f in field)
        {
            if(!isNaN(field[f]) || field[f] == "-") result += field[f];
        }

        return result;
    };

})(jQuery);

index.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="format.js"></script>
 <script type="text/javascript">

            $(function(){



                $('#price').priceFormat({
                      prefix: '',

                    thousandsSeparator: ',',
                    lakhsSeparator: "'"
                });
 $('#price1').priceFormat({
                      prefix: '',

                    thousandsSeparator: ''
                });
                });



        </script>
</head>

<body>
<input type="text" id="price">
</body>
</html>

为什么这不起作用?请给我建议。

【问题讨论】:

  • 为什么(太长)代码的哪一部分不起作用?你收到错误吗?你能缩小问题的范围吗?
  • @feeela 这实际上是针对千位分隔符的,我将其更改为十万分隔符,之后千位分隔符不能与十万分隔符一起使用,十万分隔符只能工作。我需要像 (32'32,232.33) 一样组合使用千和十万分隔符,不,没有错误。
  • 如果其中任何一个可以接受,请选择一个接受的答案。否则,请发表评论,以便可以以一种或另一种方式关闭这个问题。谢谢。
  • 请不要转储相关插件的整个源代码。如果一个标签是可用的标签,它会提供一个指向插件的链接......

标签: javascript jquery regex


【解决方案1】:

您只需将thousandsCount%5==0 添加到原始http://jquerypriceformat.com/txt/jquery.price_format.1.8.js_.txt 得到十万个数

if (thousandsCount%3==0 || thousandsCount%5==0 ) char_ = thousandsSeparator+char_;
                        thousandsFormatted = char_+thousandsFormatted;

这就是您的代码所做的。

例如数字是1234567.89

  1. 千位格式化后,数字变为 1,234,67.89
  2. 再次在第 2 步中,您的代码再次将数字格式化为 12,34567.89,但它没有将数字 1,234,67.89 作为输入,而是将原始整数值即 1234567
  3. 在 Return 中,您得到的是输出 12,34567.89 而不是您想要的输出 1,2,34,567.89(当然您的问题是这样问的)

【讨论】:

  • 谢谢...现在它只适用于 10 万,如果我们提供大量数据,它似乎不起作用,它会像这样显示 2,3,32,323.23,请告诉我
  • 这是以千和十万为单位的数字,您希望该数字如何?如果不是这个 2,3,32,323.23,那是什么?
  • 我喜欢这个一百:100.00 千:1,000.00 万:1'00,000.00 和 10'00,000.00 等等......
  • 使用这个,你可以在那里看到印度货币演示decorplanit.com/plugin,最后如果你觉得我的回答值得投票我的回答并检查它作为答案:)
  • 嗨,抱歉,我已经检查过了,我只想将数字格式化为所有货币的格式,不仅是印度卢比,在演示中它也只适用于 10 万卢比
【解决方案2】:

在 Chrome 28 中,以下内容将起作用:

Number(123456789).toLocaleString("bn-IN-u-nu-latn")
>> 12,34,56,789

这里的技巧是,由于 en-IN 语言环境指定 xxx,xxx,xxx 格式,我们使用孟加拉语语言环境,语言环境扩展名为 u-nu-latn 要求输入拉丁数字。

这似乎不适用于 Firefox 或 IE,甚至 IE10。

这显然是在使用 ECMAScript 国际化 API。见Is there an i18n (Intl) shim for JavaScript?javascript number/currency formatting等。

我个人还没有看到使用撇号的 1'23,456 格式,但如果你真的想要这样,你将不得不返回自己滚动,因为 ECMAScript 国际化 API 不支持自定义格式。

【讨论】:

    【解决方案3】:

    无需重新实现轮子,只需抓住 jQuery Globalize 并使用内置格式化程序即可。此外,使用 Globalize,您的应用将可以本地化。

    var price = Globalize.format( 123456789.00, "c", "bn-IN");  
    //-> "টা 12,34,56,789.00"
    

    注意 Globalize 可与 jQuery UI 小部件一起使用,例如 spinner

    【讨论】:

      【解决方案4】:

      我已经修改了您正在使用的插件。它将格式化数字,如 1,23,45,678.90。添加了一个新的 useLakhs 标志,所以记得也要使用它。比较原始代码和我所做的更改会让您知道哪里出了问题。

      /*
      
      * Price Format jQuery Plugin
      * Created By Eduardo Cuducos cuducos [at] gmail [dot] com
      * Currently maintained by Flavio Silveira flavio [at] gmail [dot] com
      * Version: 1.7
      * Release: 2012-02-22
      
      * original char limit by Flavio Silveira <http://flaviosilveira.com>
      * original keydown event attachment by Kaihua Qi
      * keydown fixes by Thasmo <http://thasmo.com>
      * Clear Prefix on Blur suggest by Ricardo Mendes from PhonoWay
      * original allow negative by Cagdas Ucar <http://carsinia.com>
      * keypad fixes by Carlos Vinicius <http://www.kvinicius.com.br> and Rayron Victor
      * original Suffix by Marlon Pires Junior
      * CentsLimit set to zero fixed by Jereon de Jong
      * original idea for the use of the plus sign
      
      */
      
      (function($) {
      
      /****************
      * Main Function *
      *****************/
      $.fn.priceFormat = function(options)
      {
      
          var defaults =
          {
              prefix: 'US$ ',
              suffix: '',
              centsSeparator: '.',
              thousandsSeparator: ',',
              useLakhs: false,
              lakhsSeparator: ",",
              limit: false,
              centsLimit: 2,
              clearPrefix: false,
              clearSufix: false,
              allowNegative: false,
              insertPlusSign: false
          };
      
          var options = $.extend(defaults, options);
      
          return this.each(function()
          {
              // pre defined options
              var obj = $(this);
              var is_number = /[0-9]/;
      
              // load the pluggings settings
              var prefix = options.prefix;
              var suffix = options.suffix;
              var centsSeparator = options.centsSeparator;
              var thousandsSeparator = options.thousandsSeparator;
              var lakhsSeparator = options.lakhsSeparator;
              var limit = options.limit;
              var centsLimit = options.centsLimit;
              var clearPrefix = options.clearPrefix;
              var clearSuffix = options.clearSuffix;
              var allowNegative = options.allowNegative;
              var insertPlusSign = options.insertPlusSign;
              var useLakhs = options.useLakhs;
      
              // If insertPlusSign is on, it automatic turns on allowNegative, to work with Signs
              if (insertPlusSign) allowNegative = true;
      
              // skip everything that isn't a number
              // and also skip the left zeroes
              function to_numbers (str)
              {
                  var formatted = '';
                  for (var i=0;i<(str.length);i++)
                  {
                      char_ = str.charAt(i);
                      if (formatted.length==0 && char_==0) char_ = false;
      
                      if (char_ && char_.match(is_number))
                      {
                          if (limit)
                          {
                              if (formatted.length < limit) formatted = formatted+char_;
                          }
                          else
                          {
                              formatted = formatted + char_;
                          }
                      }
                  }
      
                  return formatted;
              }
      
              // format to fill with zeros to complete cents chars
              function fill_with_zeroes (str)
              {
                  while (str.length < (centsLimit+1)) str = '0' + str;
                  return str;
              }
      
              // format as price
              function price_format(str)
              {
                  // formatting settings
                  var formatted = fill_with_zeroes(to_numbers(str));
                  var thousandsFormatted = '';
                  var thousandsCount = 0;
                  var lakhsFormatted = '';
                  var lakhsCount = 0;
      
                  // Checking CentsLimit
                  if(centsLimit == 0)
                  {
                      centsSeparator = "";
                      centsVal = "";
                  }
      
                  // split integer from cents
                  var centsVal = formatted.substr(formatted.length - centsLimit, centsLimit);
                  var integerVal = formatted.substr(0, formatted.length - centsLimit);
      
                  // apply cents pontuation
                  formatted = (centsLimit == 0) ? integerVal : integerVal + centsSeparator + centsVal;
      
                  // apply thousands pontuation
                  if (thousandsSeparator || $.trim(thousandsSeparator) != "")
                  {
                      for (var j = integerVal.length; j > 0; j--)
                      {
                          char_ = integerVal.substr(j - 1, 1);
                          thousandsCount++;
                          if (thousandsCount % 3 == 0) char_ = thousandsSeparator + char_;
                          thousandsFormatted = char_ + thousandsFormatted;
                      }
      
                      if (thousandsFormatted.substr(0, 1) == thousandsSeparator) 
                          thousandsFormatted = thousandsFormatted.substring(1, thousandsFormatted.length);
      
                      formatted = (centsLimit == 0) ? thousandsFormatted : thousandsFormatted + centsSeparator + centsVal;
                  }
      
                  // apply lakhs pontuation
                  if (useLakhs &&(lakhsSeparator || $.trim(lakhsSeparator) != ""))
                  {
                      var flag = false;
                      for (var j = integerVal.length; j > 0; j--)
                      {
                          char_ = integerVal.substr(j - 1, 1);
                          lakhsCount++;
                          if (lakhsCount % 3 == 0 && !flag) {char_ = thousandsSeparator + char_; flag = true;}
                          else if ((lakhsCount - 3) % 2 == 0 && flag) char_ = lakhsSeparator + char_;
                          lakhsFormatted = char_ + lakhsFormatted;
                      }
      
                      if (lakhsFormatted.substr(0, 1) == lakhsSeparator) 
                          lakhsFormatted = lakhsFormatted.substring(1, lakhsFormatted.length);
      
                      formatted = (centsLimit == 0) ? lakhsFormatted : lakhsFormatted + centsSeparator + centsVal;
                  }
      
      
                  // if the string contains a dash, it is negative - add it to the begining (except for zero)
                  if (allowNegative && str.indexOf('-') != -1 && (integerVal != 0 || centsVal != 0))
                      formatted = '-' + formatted;
                  else if (insertPlusSign && (integerVal != 0 || centsVal != 0))
                      formatted = '+' + formatted;
      
                  // apply the prefix
                  if (prefix) formatted = prefix + formatted;
      
                  // apply the suffix
                  if (suffix) formatted = formatted + suffix;
      
                  return formatted;
              }
      
              // filter what user type (only numbers and functional keys)
              function key_check (e)
              {
                  var code = (e.keyCode ? e.keyCode : e.which);
                  var typed = String.fromCharCode(code);
                  var functional = false;
                  var str = obj.val();
                  var newValue = price_format(str + typed);
      
                  // allow key numbers, 0 to 9
                  if((code >= 48 && code <= 57) || (code >= 96 && code <= 105)) functional = true;
      
                  // check Backspace, Tab, Enter, Delete, and left/right arrows
                  if (code ==  8) functional = true;
                  if (code ==  9) functional = true;
                  if (code == 13) functional = true;
                  if (code == 46) functional = true;
                  if (code == 37) functional = true;
                  if (code == 39) functional = true;
      
                  // Minus Sign, Plus Sign
                  if (allowNegative && (code == 189 || code == 109)) functional = true; // dash as well
                  if (insertPlusSign && (code == 187 || code == 107)) functional = true;
      
                  if (!functional)
                  {
                      e.preventDefault();
                      e.stopPropagation();
                      if (str!=newValue) obj.val(newValue);
                  }
              }
      
              // inster formatted price as a value of an input field
              function price_it ()
              {
                  var str = obj.val();
                  var price = price_format(str);
                  if (str != price) obj.val(price);
              }
      
              // Add prefix on focus
              function add_prefix()
              {
                  var val = obj.val();
                  obj.val(prefix + val);
              }
      
              function add_suffix()
              {
                  var val = obj.val();
                  obj.val(val + suffix);
              }
      
              // Clear prefix on blur if is set to true
              function clear_prefix()
              {
                  if($.trim(prefix) != '' && clearPrefix)
                  {
                      var array = obj.val().split(prefix);
                      obj.val(array[1]);
                  }
              }
      
              // Clear suffix on blur if is set to true
              function clear_suffix()
              {
                  if($.trim(suffix) != '' && clearSuffix)
                  {
                      var array = obj.val().split(suffix);
                      obj.val(array[0]);
                  }
              }
      
              // bind the actions
              $(this).bind('keydown.price_format', key_check);
              $(this).bind('keyup.price_format', price_it);
              $(this).bind('focusout.price_format', price_it);
      
              // Clear Prefix and Add Prefix
              if(clearPrefix)
              {
                  $(this).bind('focusout.price_format', function()
                  {
                      clear_prefix();
                  });
      
                  $(this).bind('focusin.price_format', function()
                  {
                      add_prefix();
                  });
              }
      
              // Clear Suffix and Add Suffix
              if(clearSuffix)
              {
                  $(this).bind('focusout.price_format', function()
                  {
                      clear_suffix();
                  });
      
                  $(this).bind('focusin.price_format', function()
                  {
                      add_suffix();
                  });
              }
      
              // If value has content
              if ($(this).val().length>0)
              {
                  price_it();
                  clear_prefix();
                  clear_suffix();
              }
          });
      };
      
      /**********************
      * Remove price format *
      ***********************/
      $.fn.unpriceFormat = function(){
        return $(this).unbind(".price_format");
      };
      
      /******************
      * Unmask Function *
      *******************/
      $.fn.unmask = function(){
      
          var field = $(this).val();
          var result = "";
      
          for(var f in field)
          {
              if(!isNaN(field[f]) || field[f] == "-") result += field[f];
          }
      
          return result;
      };
      
      })(jQuery);
      
      $(function(){
      $('#price').priceFormat({
          prefix: 'Rs. ',
          thousandsSeparator: ',',
          lakhsSeparator: "'",
          useLakhs: true
      });
      });
      

      让我知道这对你有什么作用。

      【讨论】:

        猜你喜欢
        • 2016-02-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多