Skip to content

Commit

Permalink
WIP - %f conversion specifier
Browse files Browse the repository at this point in the history
  • Loading branch information
bnoordhuis committed Jul 30, 2011
1 parent d3d8f1b commit 694a7e2
Showing 1 changed file with 23 additions and 4 deletions.
27 changes: 23 additions & 4 deletions lib/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,22 @@
var events = require('events');


var formatRegExp = /%[sdj%]/g;
/**
* Format a floating point value.
* @param value Floating point value to format.
* @param precision Precision in decimals after the dot (1, 2, 3, etc.).
*/
var MULTIPLIERS = [1, 10, 100, 1000, 10000];
function format_float(value, precision) {
if (!precision) return ~~value + ''; // integer part only
var multiplier = MULTIPLIERS[precision] || Math.pow(10, precision);
value = 5 + ~~(value * multiplier * 10);
value = (value - (value % 10)) / 10;
return ~~(value / multiplier) + '.' + ('' + value).slice(-precision);
}


var formatRegExp = /%[sdj%]|%(\.\d*)?f/g;
exports.format = function(f) {
if (typeof f !== 'string') {
var objects = [];
Expand All @@ -34,14 +49,18 @@ exports.format = function(f) {

var i = 1;
var args = arguments;
var str = String(f).replace(formatRegExp, function(x) {
switch (x) {
var str = String(f).replace(formatRegExp, function(s) {
switch (s) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
case '%j': return JSON.stringify(args[i++]);
case '%%': return '%';
default:
return x;
if (s[s.length-1] === 'f') {
var precision = s.slice(2, -1) || 6; // 6 = default precision
return format_float(args[i++], ~~precision);
}
return s;
}
});
for (var len = args.length, x = args[i]; i < len; x = args[++i]) {
Expand Down

0 comments on commit 694a7e2

Please sign in to comment.