Monday, May 9, 2011

Number format in javascript and php

In PHP, number_format() is a built-in function for formatting of an integer or float number with grouped thousands. But, in javascript, there is no such function for formatting of a number. We need to define write own custom function in javascript which will work exactly like number_format() function in PHP.

PHP
string number_format ( float $number [, int $decimals = 0 ] )
string number_format (float $number , int $decimals = 0 , string $dec_point = '.' , string $thousands_sep = ',')
Example:
<?php
$number=10527;  echo number_format($number);
// output will be 10,527
$number=1052.87;  echo number_format($number); 
//output will be 1,053
$number=105246.87;  echo number_format($number,3,'.','\''); 
//output will be 105'246.870 . Here, I have specified thousand separator as '. Default thousand separator is ,
 ?>
Note: in this function, 2nd, 3rd and 4th parameter are optional. But, if u supply 3rd parameter, 4th parameter becomes mandatory. Otherwise, it can generate warning message - Wrong parameter count.

Javascript:
<script language="javascript">
function number_format(a, b, c, d) {
 a = Math.round(a * Math.pow(10, b)) / Math.pow(10, b);
 e = a + '';
 f = e.split('.');
 if (!f[0]) {
 f[0] = '0';
 }
 if (!f[1]) {
 f[1] = '';
 }
 if (f[1].length < b) {
 g = f[1];
 for (i=f[1].length + 1; i <= b; i++) {
 g += '0';
 }
 f[1] = g;
 }
 if(d != '' && f[0].length > 3) {
 h = f[0];
 f[0] = '';
 for(j = 3; j < h.length; j+=3) {
 i = h.slice(h.length - j, h.length - j + 3);
 f[0] = d + i + f[0] + '';
 }
 j = h.substr(0, (h.length % 3 == 0) ? 3 : (h.length % 3));
 f[0] = j + f[0];
 }
 c = (b <= 0) ? '' : c;
 return f[0] + c + f[1];
}

Example:
 var number=105246.87;
document.write(number_format(number,1,'.','\''));
// output will be 105'246.9
</script>

Please do not hesitate to give your valuable suggestions.

Important queries based formulas to watch performance of a MySQL based application

(1) Session Vs global status variables value select G.variable_name,G.variable_value GlobalValue,S.variable_value SessionValue from (selec...