Site icon Anthony Carbon

Separated number in comma and decimal point using PHP or JS number format.

Separated number in comma and decimal point using PHP or JS number format. Commonly used in the price format and number separator. Hopefully this can help you.

PHP: Found this post https://www.w3schools.com/php/func_string_number_format.asp and the codes below is the sample usage of the PHP code.

echo number_format("1000000"); // output will be 1,000,000
echo number_format("1000000",2); // output will be 1,000,000.00
echo number_format("1000000",2,",","."); // output will be 1.000.000,00

JS: Found this post https://gist.github.com/rd13/3924792 and the codes below is the sample usage of the JS code.

String.prototype.number_format = function(d) {
    var n = this;
    var c = isNaN(d = Math.abs(d)) ? 2 : d;
    var s = n < 0 ? "-" : "";
    var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
    return s + (j ? i.substr(0, j) + ',' : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + ',') + (c ? '.' + Math.abs(n - i).toFixed(c).slice(2) : "");
}
// output will be 632,295.00
console.log(
'632295'.number_format() 
);
Exit mobile version