如何在jquery number_format()中包含decimal;

时间:2017-08-25 07:16:04

标签: jquery

我有这个函数,我从stacksoverflow中的其他线程中取出,使我的数字格式正确,从1000到1000 但是这段代码删除了十进制

function number_format(number, decimals, dec_point, thousands_sep) {
  // Strip all characters but numerical ones.
  number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
  var n = !isFinite(+number) ? 0 : +number,
    prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
    sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
    dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
    s = '',
    toFixedFix = function(n, prec) {
      var k = Math.pow(10, prec);
      return '' + Math.round(n * k) / k;
    };

  // Fix for IE parseFloat(0.55).toFixed(0) = 0;
  s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');

  if (s[0].length > 3) {
    s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
  }

  if ((s[1] || '').length < prec) {
    s[1] = s[1] || '';
    s[1] += new Array(prec - s[1].length + 1).join('0');
  }

  return s.join(dec);
}

我想要这种格式1,000.76,但我不知道如何修改它TYIA

2 个答案:

答案 0 :(得分:0)

您可以使用REGEX来获取逗号和小数,而不是大函数:

function digits(str){ 
    str += '';
    return str.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
}

console.log(digits(10008.20));
console.log(digits(1000.76));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 1 :(得分:0)

我使用此功能验证项目中的货币和金额,如果需要,请试一试。该功能适用​​于这种情况:

  • 1200(简单数字=> 1200.00)
  • 1,123.45(美国格式货币)
  • +1200或-1200(带符号的数字)
  • 124.5(一位小数=> 124.50)
  • 0.45(十进制)
  • .45(十进制无零=&gt; 0.45)
  • +。1(符号和小数,不带零=&gt; +0.10)

您可以选择要验证的小数位数。我使用两个,但你可以改变它。

// change this to test
var amount = "1000.76";

function validateAmount(amount){
		amount = amount.trim();
    
		var result = "", comma =",", dot=".";
    
    // check if amount is in american currency format, comma as thousand separator and dot and decimal
    var usRegExp = new RegExp("^(\-|[+]?)(([1-9][0-9]{0,2}(,[0-9]{3})*)|[0-9]+)?((\.)?|(\.?[0-9]{1,2})?)$")

    // test if amount is a number or is formatted as currency  
    if(usRegExp.test(amount))
    {
      var decimalSep = dot, thousandSep = comma

      var vals = amount.split(decimalSep)

      // remove thousand separator
      vals[0] = vals[0].replace(thousandSep, '')

      // add thousand separator to floor part of the number
      var integer = vals[0].replace(/\B(?=(\d{3})+(?!\d))/g, thousandSep)

      // if amount start with comma or dot, trasform to decimal
      if(typeof integer == 'undefined' || integer == '')
        integer = '0'+ integer

      // if amount is only + or - add zero after the sign	
      if(integer == '-' || integer == '+')	
        integer += '0'

      if(amount.indexOf(decimalSep) != -1)
      {
        decimal = vals[1]

        // amount has decimals
        if(decimal != 'undefined' && decimal != '')
        {
          if(decimal.length == 2)
          {
            result = integer + dot + decimal;
          }

          // if has more than two decimals throw error
          if(decimal.length > 2)
          {
            // here you can check decimal lenght and throw error or manage it
            console.log("more than two decimal")
          }
          // only one decimal add zero
          else if(decimal.length == 1)
          {
            result = integer + dot + decimal + '0';
          }
        }
        // amount end with comma
        else
          result = integer + dot + '00';

      }
      // simple amount without decimal, add dot and decimal part
      else
      {
        result = integer + dot + '00'
      }
    }
    else
    {	
      // throw error is not a value number
      console.log("error")
    }
    
    return result;
}

$('#id').text(validateAmount(amount))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="id" >

</div>