Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

How to print an array with at most 2 digits for float?

7 views
Skip to first unread message

mepython

unread,
Mar 2, 2005, 12:58:38 PM3/2/05
to
I like to print following:
[["Customer", "John", 84.9535929148379, ["USE", 10.0]], ["IN",
84.9535929148379], ["USE", 94.9535929148379], ["OUT",
94.9535929148379]]

like

[["Customer", "John", 84.95, ["USE", 10.0]], ["IN", 84.95], ["USE",
94.95], ["OUT", 94.95]]


I tried with pp, but it does not truncate floats. Items in Array can be
arbitary in length.

Csaba Henk

unread,
Mar 2, 2005, 1:30:58 PM3/2/05
to

Yes, pp gives a precise representation of the object as much as
possible, and I like it this way...

In similar situation I just use the following hack:

x # => 45.235234
(100 * x).to_i.to_f / 100 # => 45.23

You can make a float method of it to hide the clutter :)

But maybe there is a better way...

I see you want to do it recursively, but I guess that's not a problem to
implement.

Csaba

Robert Klemme

unread,
Mar 2, 2005, 3:00:25 PM3/2/05
to

"mepython" <a...@agni.us> schrieb im Newsbeitrag
news:1109786318....@l41g2000cwc.googlegroups.com...

Not 100% what you want though...

conv = lambda do |e|
case e
when String
e
when Enumerable
e.map &conv
when Float
sprintf( "%3.2f", e )
else
e
end
end

a= [["Customer", "John", 84.9535929148379, ["USE", 10.0]], ["IN",


84.9535929148379], ["USE", 94.9535929148379], ["OUT",
94.9535929148379]]

a.map &conv

?> a.map &conv
=> [["Customer", "John", "84.95", ["USE", "10.00"]], ["IN", "84.95"],

["USE", "94.95"], ["OUT", "94.95"]]

inj = lambda do |(f,s),e|
s << ", " if f

case e
when String
s << e.inspect
when Enumerable
s << "["
e.inject([false, s], &inj)
s << "]"
when Float
s << sprintf( "%3.2f", e )
else
s << e.inspect
end

[true,s]
end

puts( a.inject([false, ""],&inj)[1] << "]" )

>> puts( a.inject([false, ""],&inj)[1] << "]" )
["Customer", "John", 84.95, ["USE", 10.00]], ["IN", 84.95], ["USE", 94.95],
["OUT", 94.95]]

Better. As usual - with #inject... :-)

Kind regards

robert

Martin DeMello

unread,
Mar 3, 2005, 12:55:45 AM3/3/05
to
> arbitary in length.A

Ugly, but if this is just for debugging purposes you can do the
following:

class Float
def inspect
if $truncate
#round to $truncate places
else
self.to_s
end
end
end

and depending on the global it'll round off or not

martin

mepython

unread,
Mar 3, 2005, 12:41:57 PM3/3/05
to
This should serve my purpose. Thanks.

0 new messages