Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the JS equivalent to the PHP function number_format?

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?

like image 613
RONE Avatar asked Oct 10 '12 13:10

RONE


People also ask

Does PHP Number_format round?

The PHP number_format() function is used for formatting numbers with decimal places and thousands separators, but it also rounds numbers if there are more decimal places in the original number than required. As with round() it will round up on 5 and down on < 5.

How do you format numbers in JavaScript?

JavaScript numbers can be formatted in different ways like commas, currency, etc. You can use the toFixed() method to format the number with decimal points, and the toLocaleString() method to format the number with commas and Intl. NumberFormat() method to format the number with currency.


2 Answers

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); } 
like image 162
Umair Hamid Avatar answered Sep 29 '22 03:09

Umair Hamid


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}) 
like image 41
Ahmed-Anas Avatar answered Sep 29 '22 02:09

Ahmed-Anas