最新消息:

Axure数字的千分位格式化(注入JS)

其它教程 Jorkin 34浏览
Number.prototype.formatWithCommas = function (decimalPlaces = 2) {
  return this.toString().formatWithCommas(decimalPlaces);
};
String.prototype.formatWithCommas = function (decimalPlaces = 2) {
  if (!/^-?\d*\.?\d+$/.test(this)) {
    return this;
  }
  let [integerPart, decimalPart = ''] = this.split('.');
  let isNegative = integerPart.startsWith('-');
  if (isNegative) {
    integerPart = integerPart.slice(1);
  }
  let formattedInteger = '';
  let count = 0;
  for (let i = integerPart.length - 1; i >= 0; i--) {
    formattedInteger = integerPart[i] + formattedInteger;
    count++;
    if (count % 3 === 0 && i !== 0) {
      formattedInteger = ',' + formattedInteger;
    }
  }
  if (isNegative) {
    formattedInteger = '-' + formattedInteger;
  }
  if (decimalPlaces > 0) {
    decimalPart = decimalPart.padEnd(decimalPlaces, '0').slice(0, decimalPlaces);
    return `${formattedInteger}.${decimalPart}`;
  } else {
    return formattedInteger;
  }
};

压缩后代码:

Number.prototype.formatWithCommas=function(e=2){return this.toString().formatWithCommas(e)};
String.prototype.formatWithCommas=function(e=2){if(!/^-?\d*\.?\d+$/.test(this))return this;let[t,n=""]=this.split("."),r=t.startsWith("-");r&&(t=t.slice(1));let o="",i=0;for(let s=t.length-1;s>=0;s--){o=t[s]+o,i++,i%3==0&&s!==0&&(o=","+o)}return r&&(o="-"+o),e>0?(n=n.padEnd(e,"0").slice(0,e),o+"."+n):o};

如果觉得我的教程做的不错呢,欢迎关注、收藏、转发、捐赠,谢谢。

原文链接:Axure数字的千分位格式化(注入JS)

转载请注明:最InのAxure » Axure数字的千分位格式化(注入JS)