Skip to content
Browse files

WIP - %f conversion specifier

  • Loading branch information...
1 parent d3d8f1b commit 694a7e26ddb526d3348cfd3d1e82bc082b619666 @bnoordhuis committed Jul 31, 2011
Showing with 23 additions and 4 deletions.
  1. +23 −4 lib/util.js
View
27 lib/util.js
@@ -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 = [];
@@ -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]) {

0 comments on commit 694a7e2

Please sign in to comment.
Something went wrong with that request. Please try again.