Formatting strings in JavaScript
<p>I'm trying to convert a file size represented in bytes in JavaScript as follows (HTML 5).</p>

<pre><code>function formatBytes(bytes)
{
    var sizes = ['Bytes', 'kB', 'MB', 'GB', 'TB'];
    if (bytes == 0) 
    {
        return 'n/a';
    }
    var i = parseInt(Math.log(bytes) / Math.log(1024));
    return Math.round(bytes / Math.pow(1024, i), 2) + sizes[i];
}
</code></pre>

<p>But I need to represent the file size in both SI and binary units as and when required like,</p>

<pre><code>kB&lt;---&gt;KiB
MB&lt;---&gt;MiB
GB&lt;---&gt;GiB
TB&lt;---&gt;TiB
EB&lt;---&gt;EiB
</code></pre>

<p>This could be done in Java like the following (using one additional boolean parameter to the method).</p>

<pre><code>public static String formatBytes(long size, boolean si)
{
    final int unitValue = si ? 1000 : 1024;
    if (size &lt; unitValue) 
    {
        return size + " B";
    }
    int exp = (int) (Math.log(size) / Math.log(unitValue));
    String initLetter = (si ? "kMGTPE" : "KMGTPE").charAt(exp-1) + (si ? "" : "i");
    return String.format("%.1f %sB", size / Math.pow(unitValue, exp), initLetter);
}
</code></pre>

<p>Somewhat equivalent code in JavaScript could be as follows.</p>

<pre><code>function formatBytes(size, si)
{
    var unitValue = si ? 1000 : 1024;
    if (size &lt; unitValue) 
    {
        return size + " B";
    }
    var exp = parseInt((Math.log(size) / Math.log(unitValue)));
    var initLetter = (si ? "kMGTPE" : "KMGTPE").charAt(exp-1) + (si ? "" : "i");
    alert(size / Math.pow(unitValue, exp)+initLetter);
    //return String.format("%.1f %sB", size / Math.pow(unitValue, exp), initLetter);
}
</code></pre>

<p>I couldn't write the equivalent statement in JavaScript as the commented line in the preceding snippet (the last one) indicates. Of course, there are other ways to do this in JavaScript but I'm looking for a concise way and more precisely, if it is possible to write the equivalent statement in JavaScript/jQuery. Is it possible?</p>
