79

PHP函数:

function formatNumberForDisplay($number, $decimal=0, $decimalSeperator='.', $numberSeperator=',')
{
     return number_format($number, $decimal, $decimalSeperator, $numberSeperator);
}

任何人都可以向我建议 jQuery/JavaScript 中的等效功能吗?

4

13 回答 13

106

可以在此处找到与 js 中的 number_format 相同的等价物

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);
}
于 2015-12-07T19:42:29.190 回答
50

只需toLocaleString在整数对象上使用。

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString#Browser_compatibility

let x = 1234567;
//if x is a string/non-number, use parseInt/parseFloat to convert to a number. Thanks @Aleksandr Kopelevich
x.toLocaleString('us', {minimumFractionDigits: 2, maximumFractionDigits: 2})
于 2016-12-15T07:47:07.887 回答
49

这是你想要得到的吗?

yourFloatVarHere.toFixed(2);

瞧。

于 2013-01-15T19:16:22.013 回答
19

本机“国际”对象方法:

var amount = 5000.25;
var locale = 'de';
var options = {style: 'currency', currency: 'eur', minimumFractionDigits: 2, maximumFractionDigits: 2};
var formatter = new Intl.NumberFormat(locale, options);

console.log(formatter.format(amount));

http://jsfiddle.net/arturrelax/sa9jL138/1/

更多信息请访问:https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl

于 2014-12-12T08:01:52.537 回答
15

我知道这是一个旧线程,但我制作了自己的函数,它是纯 Javascript 的。

简单的解决方案

https://gist.github.com/VassilisPallas/d73632e9de4794b7dd10b7408f7948e8/bf17eccef8521b4e5869bdc6a5b09a771356fbff

这适用于有限数字

function number_format(number, decimals, dec_point, thousands_point) {

    if (number == null || !isFinite(number)) {
        throw new TypeError("number is not valid");
    }

    if (!decimals) {
        var len = number.toString().split('.').length;
        decimals = len > 1 ? len : 0;
    }

    if (!dec_point) {
        dec_point = '.';
    }

    if (!thousands_point) {
        thousands_point = ',';
    }

    number = parseFloat(number).toFixed(decimals);

    number = number.replace(".", dec_point);

    var splitNum = number.split(dec_point);
    splitNum[0] = splitNum[0].replace(/\B(?=(\d{3})+(?!\d))/g, thousands_point);
    number = splitNum.join(dec_point);

    return number;
}

复杂的解决方案

这解决了大数字的问题

https://gist.github.com/VassilisPallas/d73632e9de4794b7dd10b7408f7948e8

 const splitThousands = (number) => (dec_point, thousands_point) => {
  const splitNum = number.toString().split(dec_point);
  splitNum[0] = splitNum[0].replace(/\B(?=(\d{3})+(?!\d))/g, thousands_point);
  return splitNum.join(dec_point);
};

const isBigNumber = (number) => number.toString().includes("e");

const isBigFloat = (number) => number.toString().includes("-");

const calcTrailing = (dec, len) => Number(dec) + 2 - len;

const handleBigFloats = (number, decimals) => {
  if (!decimals) {
    return "0";
  }

  const [numbers, dec] = number.toString().replace(".", "").split("e-");
  const trailingZeros = calcTrailing(dec, numbers.length);
  const res = `${"0.".padEnd(trailingZeros + 2, "0")}${numbers}`;

  return decimals ? res.substring(0, 2) + res.substring(2, decimals + 2) : res;
};

const handleBigNumbers = (number, decimals, dec_point, thousands_point) => {
  if (isBigFloat(number)) {
    return handleBigFloats(number, decimals);
  }

  return splitThousands(BigInt(number))(dec_point, thousands_point);
};

function handleFiniteNumbers(number, decimals, dec_point, thousands_point) {
  if (!isFinite(number)) {
    throw new TypeError("number is not finite number");
  }

  if (!decimals) {
    const len = number.toString().split(".").length;
    decimals = len > 1 ? len : 0;
  }

  return splitThousands(
    parseFloat(number).toFixed(decimals).replace(".", dec_point)
  )(dec_point, thousands_point);
}

const numberFormat = (
  number,
  decimals,
  dec_point = ".",
  thousands_point = ","
) => {
  if (number == null || typeof number !== "number") {
    throw new TypeError("number is not valid");
  }

  if (isBigNumber(number)) {
    return handleBigNumbers(number, decimals, dec_point, thousands_point);
  }

  return handleFiniteNumbers(number, decimals, dec_point, thousands_point);
};

https://jsfiddle.net/p2ft9n4v/1/

于 2017-08-16T08:53:09.970 回答
12

更接近 php 的函数number_format($number)应该是number.toLocaleString('en')javascript

于 2020-01-17T22:08:27.033 回答
6

这是另一个简短的解决方案,它的行为应该类似于 php 等效项。

function number_format(number,decimals,dec_point,thousands_sep) {
    number  = number*1;//makes sure `number` is numeric value
    var str = number.toFixed(decimals?decimals:0).toString().split('.');
    var parts = [];
    for ( var i=str[0].length; i>0; i-=3 ) {
        parts.unshift(str[0].substring(Math.max(0,i-3),i));
    }
    str[0] = parts.join(thousands_sep?thousands_sep:',');
    return str.join(dec_point?dec_point:'.');
}
于 2016-01-15T18:05:26.463 回答
3

这是一个简单的函数,您可以使用它在 php 中实现与 number_format 几乎相同的结果:

function number_format(user_input){
    var filtered_number = user_input.replace(/[^0-9]/gi, '');
    var length = filtered_number.length;
    var breakpoint = 1;
    var formated_number = '';

    for(i = 1; i <= length; i++){
        if(breakpoint > 3){
            breakpoint = 1;
            formated_number = ',' + formated_number;
        }
        var next_letter = i + 1;
        formated_number = filtered_number.substring(length - i, length - (i - 1)) + formated_number; 

        breakpoint++;
    }

    return formated_number;
}

另一种方法是使用 ajax 调用 php 脚本,在该脚本中对数字运行 number_format 并将 ajax 作为字符串返回。但是有点乱

于 2014-11-24T12:09:05.090 回答
1

这并不容易,尝试使用简单的 jquery 插件,例如:

jquery-数字格式化程序

Jquery-价格格式

于 2012-10-10T13:24:48.860 回答
0

我对此的看法:

var number_format = function(num) {
  stringNum = num.toString();
  stringNum = stringNum.split("");
  c = 0;
  if (stringNum.length>3) {
    for (i=stringNum.length; i>-1; i--) {
      if ( (c==3) && ((stringNum.length-i)!=stringNum.length) ) {
        stringNum.splice(i, 0, ",");
        c=0;
      }
      c++
    }
    return stringNum;
  }
  return num;
}

$("body").append(number_format(100000000));
于 2016-09-27T08:24:55.990 回答
0

暴露示例的另一种变体:

const numberFormat = (value, decimals, decPoint, thousandsSep) => {
    decPoint = decPoint || '.';
    decimals = decimals !== undefined ? decimals : 2;
    thousandsSep = thousandsSep || ' ';

    if (typeof value === 'string') {
        value = parseFloat(value);
    }

    let result = value.toLocaleString('en-US', {
        maximumFractionDigits: decimals,
        minimumFractionDigits: decimals
    });

    let pieces = result.split('.');
    pieces[0] = pieces[0].split(',').join(thousandsSep);

    return pieces.join(decPoint);
};
于 2018-12-27T12:31:27.090 回答
0

JS 等价物将是:

var number = //input value

parseFloat(number).toFixed(3);
于 2021-11-02T17:30:38.043 回答
-3

我要做的只是按如下方式调用 JS 函数并且它可以工作:

var formattedNumber = number_format(value)
于 2019-05-10T12:25:17.857 回答