truncate float to 2 decimals

Discussion in 'Ruby' started by Junkone, Aug 13, 2008.

  1. Junkone

    Junkone Guest

    how do i truncate the float to 2 decimals

    irb(#<Object:0x3d95578>):001:0> f=0.911501706632285
    => 0.911501706632285
     
    Junkone, Aug 13, 2008
    #1
    1. Advertisements

  2. Junkone

    ara.t.howard Guest

    just use the normal math way

    cfp:~ > cat a.rb
    float = 0.911501706632285

    puts( Integer(float * 100) / Float(100) )


    cfp:~ > ruby a.rb
    0.91




    a @ http://codeforpeople.com/
     
    ara.t.howard, Aug 13, 2008
    #2
    1. Advertisements

  3. Junkone

    Tim Hunter Guest

    Do you really want to change f?

    f2 = (f*100).to_i / 100.0

    Or do you just want to display f with 2 decimals?

    "%5.2f" % f
     
    Tim Hunter, Aug 13, 2008
    #3
  4. Junkone

    James Gray Guest

    => "0.91"

    James Edward Gray II
     
    James Gray, Aug 13, 2008
    #4
  5. Junkone

    Trans Guest

    With Facets:

    require 'facets/float/round'

    f=0.911501706632285

    f.round_at(2)

    or

    f.round_to(.01)

    Also, Ruby 1.9 modifies #round to take a decimal place, I believe.

    T.
     
    Trans, Aug 13, 2008
    #5
  6. Junkone

    Tom Reilly Guest

    You might also try :
    puts (((float * 100.0).round / 100.0).to_i)
     
    Tom Reilly, Aug 14, 2008
    #6
    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.