What is the JS equivalent to the PHP function number_format?

PhpJavascriptJquery

Php Problem Overview


PHP Function:

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

Can anybody suggest to me the equivalent functionality in jQuery/JavaScript?

Php Solutions


Solution 1 - Php

The same equivalent of number_format in js can found here

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);
}

Solution 2 - Php

Just use toLocaleString on an integer object.

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})

Solution 3 - Php

is this what you'd like to get?

yourFloatVarHere.toFixed(2);

voilà.

Solution 4 - Php

Native "Intl" object approach:

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/

More information at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl

Solution 5 - Php

I know it's an old thread, but I made my own function, which is in pure Javascript.

Simple Solution

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

This works fine with finite numbers

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;
}

Complex Solution

This solves the issue with big numbers

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/

Solution 6 - Php

Closer function to php number_format($number) should be number.toLocaleString('en') of javascript

Solution 7 - Php

Here is another short solution that should behaviour like the php-equivalent.

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:'.');
}

Solution 8 - Php

Here is a simple function that you can use to achieve almost the same result of number_format in php:

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;
}

Another way is to use ajax to make a call to a php script where you run number_format on the number and return it with ajax as a string. But it`s a bit messy.

Solution 9 - Php

It no easy, try to use simple jquery-plugins such as:

jquery-numberformatter

Jquery-Price-Format

Solution 10 - Php

My take on this:

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));

Solution 11 - Php

Another variant of exposed examples:

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);
};

Solution 12 - Php

The JS equivalent will be:

var number = //input value

parseFloat(number).toFixed(3);

Solution 13 - Php

I'm to do it just calling the JS function as follows and it works:

var formattedNumber = number_format(value)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRONEView Question on Stackoverflow
Solution 1 - PhpUmair HamidView Answer on Stackoverflow
Solution 2 - PhpAhmed-AnasView Answer on Stackoverflow
Solution 3 - PhpMoVodView Answer on Stackoverflow
Solution 4 - PhpArturView Answer on Stackoverflow
Solution 5 - PhpVasileios PallasView Answer on Stackoverflow
Solution 6 - PhpMihai GalanView Answer on Stackoverflow
Solution 7 - PhpDennis BohnView Answer on Stackoverflow
Solution 8 - PhpspreadzzView Answer on Stackoverflow
Solution 9 - PhpRDKView Answer on Stackoverflow
Solution 10 - PhpNir TzezanaView Answer on Stackoverflow
Solution 11 - PhpМаксим КалябинView Answer on Stackoverflow
Solution 12 - PhpSubasish ProdhanView Answer on Stackoverflow
Solution 13 - PhpAjjuView Answer on Stackoverflow