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?
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.
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.
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); }
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})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With