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

Discussion in 'Ruby' started by mepython, Mar 2, 2005.

  1. mepython

    mepython Guest

    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.
     
    mepython, Mar 2, 2005
    #1
    1. Advertisements

  2. mepython

    Csaba Henk Guest

    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
     
    Csaba Henk, Mar 2, 2005
    #2
    1. Advertisements

  3. 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] << "]" )
    ["Customer", "John", 84.95, ["USE", 10.00]], ["IN", 84.95], ["USE", 94.95],
    ["OUT", 94.95]]

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

    Kind regards

    robert
     
    Robert Klemme, Mar 2, 2005
    #3
  4. 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
     
    Martin DeMello, Mar 3, 2005
    #4
  5. mepython

    mepython Guest

    This should serve my purpose. Thanks.
     
    mepython, Mar 3, 2005
    #5
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.