» Javascript equivalent for PHP's number_format

PHP to Javascript Project: php.js

php.jsThis article is part of the 'Porting PHP to Javascript' Project, which aims to decrease the gap between developing for PHP & Javascript.

A lot of people are familiar with PHP's functions, and though Javascript functions are often quite similar, some functions may be missing or addressed differently. The Javascript implementations should be as compliant with the PHP versions as possible, a good indication is that the PHP function manual could also apply to the Javascript version.

Porting crucial PHP functions to Javascript can be fun & useful. Currently some PHP functions have been added, but readers are encouraged to contribute and improve functions by adding comments. Eventually the goal is to save all the functions in one php.js file and make it publicly available for your coding pleasure.

If you choose to contribute, let me know how you want to be credited in the function's comments. You may also want to subscribe to RSS so you receive updates whenever new functions are posted.

This is a Javascript version of the PHP function: number_format.

PHP number_format

Description

number_format - Format a number with grouped thousands

string number_format ( float number[, int decimals[, string dec_point]], string thousands_sep)

number_format() returns a formatted version of number.This function accepts either one, two or four parameters (not three):

See Also

Javascript number_format

Source

This is the main source of the Javascript version of PHP's number_format

function number_format( number, decimals, dec_point, thousands_sep ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://crestidg.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)    
    // *     example 1: number_format(1234.5678, 2, '.', '');
    // *     returns 1: 1234.57     
 
    var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
    var d = dec_point == undefined ? "," : dec_point;
    var t = thousands_sep == undefined ? "." : thousands_sep, 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) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}

Examples

Currently there is 1 example

Example 1

This is how you could call number_format()
number_format(1234.5678, 2, '.', '');
And that would return
1234.57

More about this Project

Download php.js

To easily include it in your code, every function currently available is stored in

Normal

Namespaced What is 'namespaced?'

To download use Right click, Save Link As
Generally the best way is to use a minified version and gzip it



Testing the functions

The number of functions is growing fast and so it becomes hard to maintain quality.

To defeat that danger of bad code, syntax errors, etc, I've added a new feature: php.js tester.

It is an automatically generated page that includes ALL functions in your browser, and then extracts specific testing information from each function's comments. This info is then used to run the function, and the return value is compared to a predefined one.

This way code is always checked on syntax errors, and if it doesn't function correctly anymore after an update, we should also be able to detect it more easily.

If you want, go check it out.


Credits

Respect & awards go to everybody who has contributed in some way so far:

medalmedalMichael White (link) for contributing to:
 array_count_values, get_included_files, include, include_once, require, require_once, md5, number_format, parse_str, printf, sha1, sprintf, str_pad, strnatcmp, http_build_query, floatval, is_object, print_r
spacemedal_argos for contributing to:
 array_fill, array_pad, array_product, array_rand, compact, count, range, abs, defined, ip2long, long2ip, implode, strcmp, ucwords
spacemedalJonas Raoni Soares Silva (link) for contributing to:
 shuffle, abs, setcookie, number_format, number_format, soundex, str_repeat, str_replace, str_rot13, ucwords, wordwrap, wordwrap
spacemedalLegaev Andrey for contributing to:
 end, reset, file, file_get_contents, function_exists, include, include_once, http_build_query, is_array, is_object
spacemedalAtes Goral (link) for contributing to:
 array_change_key_case, array_count_values, array_diff_key, get_class, preg_quote, addslashes, count_chars, str_rot13, stripslashes
spacemedalPhilip Peterson for contributing to:
 sizeof, round, echo, nl2br, str_replace, strchr, urldecode, urlencode, var_export
spacemedalMartijn Wieringa for contributing to:
 str_ireplace, str_split, strcasecmp, stripos, strnatcmp, substr
spacemedalWebtoolkit.info (link) for contributing to:
 crc32, md5, sha1, utf8_decode, utf8_encode
 
spacemedalCarlos R. L. Rodrigues (link) for contributing to:
 array_chunk, array_unique, date, levenshtein
spacemedalAsh Searle (link) for contributing to:
 basename, printf, sprintf
spacemedalErkekjetter for contributing to:
 ltrim, rtrim, trim
spacemedalmarrtins for contributing to:
 array_change_key_case, addslashes, stripslashes
spacemedalAlfonso Jimenez (link) for contributing to:
 array_reduce, strpbrk
spacemedalAman Gupta for contributing to:
 base64_decode, utf8_decode
spacemedalArpad Ray (mailto:arpad@php.net) for contributing to:
 serialize, unserialize
spacemedalKarol Kowalski for contributing to:
 array_reverse, abs
spacemedalThunder.m for contributing to:
 base64_decode, base64_encode
spacemedalTyler Akins (link) for contributing to:
 base64_decode, base64_encode
spacemedalmdsjack (link) for contributing to:
 include, trim
spacemedalAlexander Ermolaev (link) for contributing to:
 trim
spacemedalAllan Jensen (link) for contributing to:
 number_format
spacemedalAndrea Giammarchi (link) for contributing to:
 array_map
spacemedalBayron Guevara for contributing to:
 base64_encode
spacemedalBenjamin Lupton for contributing to:
 number_format
spacemedalBrad Touesnard for contributing to:
 date
spacemedalBrett Zamir for contributing to:
 str_split
spacemedalCagri Ekin for contributing to:
 parse_str
spacemedalCord for contributing to:
 is_array
spacemedalDavid for contributing to:
 is_numeric
spacemedalDavid James for contributing to:
 get_class
spacemedalDxGx for contributing to:
 trim
spacemedalFGFEmperor for contributing to:
 mktime
spacemedalFelix Geisendoerfer (link) for contributing to:
 array_key_exists
spacemedalFremyCompany for contributing to:
 isset
spacemedalGabriel Paderni for contributing to:
 str_replace
spacemedalLeslie Hoare for contributing to:
 rand
spacemedalLincoln Ramsay for contributing to:
 basename
spacemedalMeEtc (link) for contributing to:
 date
spacemedalMick@el for contributing to:
 stripslashes
spacemedalNick Callen for contributing to:
 wordwrap
spacemedalOzh for contributing to:
 dirname
spacemedalPedro Tainha (link) for contributing to:
 unserialize
spacemedalPeter-Paul Koch (link) for contributing to:
 date
spacemedalPhilippe Baumann for contributing to:
 empty
spacemedalSakimori for contributing to:
 strlen
spacemedalSanjoy Roy for contributing to:
 array_diff
spacemedalSimon Willison (link) for contributing to:
 str_replace
spacemedalSteve Clay for contributing to:
 function_exists
spacemedalSteve Hilder for contributing to:
 strcmp
spacemedalSteven Levithan (link) for contributing to:
 trim
spacemedalT0bsn for contributing to:
 crc32
spacemedalThiago Mata (link) for contributing to:
 call_user_func_array
spacemedalTim Wiel for contributing to:
 date
spacemedalXoraX (link) for contributing to:
 dirname
spacemedalbaris ozdil for contributing to:
 mktime
spacemedalbooeyOH for contributing to:
 preg_quote
spacemedaldjmix for contributing to:
 basename
spacemedalduncan for contributing to:
 array_unique
spacemedalecho is bad for contributing to:
 echo
spacemedalgabriel paderni for contributing to:
 mktime
spacemedalger for contributing to:
 html_entity_decode
spacemedaljohn (link) for contributing to:
 html_entity_decode
spacemedalkenneth for contributing to:
 explode
spacemedalpenutbutterjelly for contributing to:
 str_ireplace
spacemedalstensi for contributing to:
 intval

Your name here?

Contributing is as easy as adding a comment with better code, or code for a new function.
Any contribution leading to improvement will directly get your name & link here.


Coming Project features

Project features that we are currently working on:

  • Versioning. Individual functions are versioned, but the entire library should be versioned as well.
  • Light. A lightweight version of php.js should be made available with only common functions in it.

Like this article?

   Then Dzone it!
Or use another bookmark button below to show your support &
help me spread the word.


tags: programming, php, javascript
category: Programming - Javascript - PHP equivalents
read: 2,282 times

Add comment

for syntax highlighting

[CODE="Javascript"]
your_code_here();
[/CODE]

Replace "Javascript"
with "php", "text", etc.
code (to make sure you are not a spammer)

Comments

#11. Kevin on 13 April 2008

Kevin@ Jonas Raoni: Thanks I've updated the function. I have one remark though. We generally compress code with packer & jsmin to obtain bandwidth & speed advantages, while maintaining readability so developers can more easily understand and update each others code.

#10. Jonas Raoni on 12 April 2008

Jonas RaoniI corrected all of the bugs that I found:
- Negative numbers;
- Starting with zero;
- Rouding (when cutting the decimal places of "0.9" it should be 1 not 0).

... [more] And here is the last version of the code:

Number.prototype.formatMoney = function(c, d, t){
var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "",
i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t)
+ (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};

#9. Howard Yeend on 09 April 2008

Howard Yeendyay for Allan Jensen. I just noticed the same bug he fixed. cheers dude.

#8. Kevin on 29 March 2008

Kevin@ Allan Jensen: Wow thanks for fixing it!

#7. Allan Jensen on 28 March 2008

Allan JensenFixed the problem with negative numbers myself. Function needs to look like this:

function number_format( number, decimals, dec_point, thousands_sep ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://crestidg.com)
    // +     bugfix by: Benjamin Lupton
  // +     bugfix by: Allan Jensen (http://www.winternet.no) (fixed formatting negative numbers)
    // *     example 1: number_format(1234.5678, 2, '.', '');
    // *     returns 1: 1234.57
 
    var i, j, kw, kd, km;
  var neg = "";
 
  // Input sanitation & defaults
  if ( isNaN(decimals = Math.abs(decimals)) ) {
    decimals = 2;
  }
  if (dec_point == undefined) {
    dec_point = ".";
  }
  if (thousands_sep == undefined) {
    thousands_sep = ",";
  }
 
  i = parseInt(number = (+number || 0).toFixed(decimals)) + "";
  if (i.substr(0,1) == "-") {
    number = Math.abs(number);
    neg = "-";
    i = i.substr(1);
  }
 
  if ((j = i.length) > 3 ) {
    j = j % 3;
  } else {
    j = 0;
  }
 
  km = (j ? i.substr(0, j) + thousands_sep : "");
  kw = i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands_sep);
  //kd = (decimals ? dec_point + Math.abs(number - i).toFixed(decimals).slice(2) : "");
  kd = (decimals ? dec_point + Math.abs(number - i).toFixed(decimals).replace(/-/, 0).slice(2) : "");
  return neg + km + kw + kd;
}

#6. Allan Jensen on 28 March 2008

Allan JensenThe function has a problem with negative numbers.

This:

number_format(-258.75, 2, ",", ".")
... [more]
incorrectly gives:

-,258,75

Please help me fix this.

#5. Kevin on 20 March 2008

Kevin@ Benjamin Lupton: Thank you!

#4. Benjamin &quot;balupton&quot; Lupton on 20 March 2008

Benjamin \"balupton\" Luptondec_point and thousands_sep defaults should be the other way round

#3. Michael White on 01 March 2008

Michael WhiteNo problem. I love having these familiar PHP functions available. I have a sort of proposal for you, maybe you could contact me via email (michael -a-t- crestidg.com) so I can get you some more details. It probably wouldn't take too much time for us to do and it would benefit those who want to use the entire PHP.js package along side other JavaScript quite a lot.

#2. Kevin on 01 March 2008

Kevin@ Michael White: It sure did, thanks for taking the time to supply better code. I've updated the function!

#1. Michael White on 01 March 2008

Michael WhiteThere is a bug in Safari - at least in Safari 3.0.4 that causes the combination of Math.abs(0).toFixed(x) where x seems to be any positive integer to provide erroneous output. The sample code below contains problematic code at the top and a sample solution line at the end. The new code for the number_format() function actually is in a separate code block below this one.

var price = 0.00;
alert(Math.abs(price)); // Alerts: 0 - correct.
  
// Alerts: 0.00 in most browsers.
// In Safari 3.0.4 you get: 0.-0
alert(Math.abs(price).toFixed(2));
  
// However - If you skip the use of Math.abs() on a 0 value then the toFixed() function works correctly.
var new_price = 0;
alert(new_price.toFixed(2));
  
// Temp-fix ( I submitted this bug to Apple)
var num = 0;
var result = Math.abs(0).toFixed(1);
alert(result);
result = result.replace(/-/, 0);
alert(result);
Since this problem only occurs when working on a value of 0 (zero) to begin with we know that the hyphen character should be a 0 so we can simply replace it with a 0 if it is found.
// The easiest way to fix this is to simply modify the line that reads:
kd = (decimals ? dec_point + Math.abs(number - i).toFixed(decimals).slice(2) : "");
 
// with the following line of code:
kd = (decimals ? dec_point + Math.abs(number - i).toFixed(decimals).replace(/-/, 0).slice(2) : "");
 
// The only difference is the addition of .replace(/-/, 0) just before the slice() method is used.
// This tiny extra amount of processing should not be significant unless number_format() is run in very tight loops - and even then it can only be considered extra in browsers like IE, Opera, and Firefox since this appears to be a Safari only bug. Checking the browser seemed to be overkill in this instance.
I hope it helps! Michael White - 2008 michael -a-t- crestidg.com http://crestidg.com/