---
layout: page
title: "JavaScript printf function"
comments: true
sharing: true
footer: true
alias:
- /functions/view/printf:494
- /functions/view/printf
- /functions/view/494
- /functions/printf:494
- /functions/494
---
<!-- Generated by Rakefile:build -->
A JavaScript equivalent of PHP's printf

{% codeblock strings/printf.js lang:js https://raw.github.com/kvz/phpjs/master/functions/strings/printf.js raw on github %}
function printf () {
  // From: http://phpjs.org/functions
  // +   original by: Ash Searle (http://hexmen.com/blog/)
  // +   improved by: Michael White (http://getsprink.com)
  // +   improved by: Brett Zamir (http://brett-zamir.me)
  // -    depends on: sprintf
  // *     example 1: printf("%01.2f", 123.1);
  // *     returns 1: 6

  var body, elmt, d = this.window.document;
  var ret = '';

  var HTMLNS = 'http://www.w3.org/1999/xhtml';
  body = d.getElementsByTagNameNS
    ? (d.getElementsByTagNameNS(HTMLNS, 'body')[0]
      ? d.getElementsByTagNameNS(HTMLNS, 'body')[0]
      : d.documentElement.lastChild)
    : d.getElementsByTagName('body')[0];

  if (!body) {
    return false;
  }

  ret = this.sprintf.apply(this, arguments);

  elmt = d.createTextNode(ret);
  body.appendChild(elmt);

  return ret.length;
}
{% endcodeblock %}

 - [Raw function on GitHub](https://github.com/kvz/phpjs/blob/master/functions/strings/printf.js)

Please note that php.js uses JavaScript objects as substitutes for PHP arrays, they are 
the closest match to this hashtable-like data structure. 

Please also note that php.js offers community built functions and goes by the 
[McDonald's Theory](https://medium.com/what-i-learned-building/9216e1c9da7d). We'll put online 
functions that are far from perfect, in the hopes to spark better contributions. 
Do you have one? Then please just: 

 - [Edit on GitHub](https://github.com/kvz/phpjs/edit/master/functions/strings/printf.js)

### Example 1
This code
{% codeblock lang:js example %}
printf("%01.2f", 123.1);
{% endcodeblock %}

Should return
{% codeblock lang:js returns %}
6
{% endcodeblock %}


### Other PHP functions in the strings extension
{% render_partial _includes/custom/strings.html %}
