Permalink
Browse files

Global float rounding for prettier output

My solution is kind of hacky but it seems like there is no better option.
See http://stackoverflow.com/questions/1447287/format-floats-with-standard-json-module
  • Loading branch information...
1 parent c7dcf9a commit f0f9b2ac99118f513f5bf0fd5f7628d1f6ddb590 @sadimusi sadimusi committed Apr 4, 2012
Showing with 41 additions and 2 deletions.
  1. +38 −0 burger/roundedfloats.py
  2. +3 −2 munch.py
View
@@ -0,0 +1,38 @@
+#!/usr/bin/env python
+# -*- coding: utf8 -*-
+"""
+Copyright (c) 2011 Tyler Kenendy <tk@tkte.ch>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+"""
+
+
+def transform_floats(o):
+ if isinstance(o, float):
+ return RoundedFloat(o)
+ elif isinstance(o, dict):
+ return dict((k, transform_floats(v)) for k, v in o.iteritems())
+ elif isinstance(o, (list, tuple)):
+ return map(transform_floats, o)
+ return o
+
+
+class RoundedFloat(float):
+ def __repr__(self):
+ return "%.5g" % self
View
@@ -36,6 +36,7 @@
from solum import JarFile
from burger.website import Website
+from burger.roundedfloats import transform_floats
def import_toppings():
@@ -239,9 +240,9 @@ def __repr__(self):
summary.append(aggregate)
if not compact:
- json.dump(summary, output, sort_keys=True, indent=4)
+ json.dump(transform_floats(summary), output, sort_keys=True, indent=4)
else:
- json.dump(summary, output)
+ json.dump(transform_floats(summary), output)
# Cleanup temporary downloads
if download_fresh_jar:

0 comments on commit f0f9b2a

Please sign in to comment.