round the floating point to nearest halfpoint

Discussion in 'Ruby' started by Lucky Nl, May 26, 2010.

  1. Lucky Nl

    Lucky Nl Guest

    Hi ,
    I want to round the my floating point result into nearest halfpoint
    how to do it.
    Example:
    1)My floating point result is 3.3
    i want it become 3.5
    2) My floating point result is 3.6
    i want it become 4


    How can we do it
    --
    Posted via http://www.ruby-forum.com/.
    Lucky Nl, May 26, 2010
    #1
    1. Advertising

  2. 2010/5/26 Lucky Nl <>:
    > =A0I want to round the my floating point result into nearest halfpoint
    > .how to do it.
    > =A0Example:
    > =A0 1)My floating point result is 3.3
    > =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0i want it become 3.5
    > =A02) My floating point result is 3.6
    > =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0i want it become 4


    If you are rounding then 3.6 should yield 3.5 because (3.6 - 3.5) <<
    (4 - 3.6). Otherwise you want the ceiling function.

    > How can we do it


    irb(main):012:0> [3.3, 3.6].map {|x| (x * 2).round / 2.0}
    =3D> [3.5, 3.5]
    irb(main):014:0> [3.3, 3.6].map {|x| (x * 2).ceil / 2.0}
    =3D> [3.5, 4.0]

    Btw, I would rather not round float values and use them as they are.
    If at all I would usually only round them for output.

    Cheers

    robert

    --=20
    remember.guy do |as, often| as.you_can - without end
    http://blog.rubybestpractices.com/
    Robert Klemme, May 26, 2010
    #2
    1. Advertising

  3. On 26 May 2010 15:09, Robert Klemme <> wrote:
    >
    > robert
    >

    Arf, you answered before I did finish my answer.

    .. was looking the exact names for rounding in BigDecimal.mode ..

    Regards,
    B.D.
    Benoit Daloze, May 26, 2010
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. John Smith

    floating point round in C++

    John Smith, Dec 14, 2003, in forum: C++
    Replies:
    2
    Views:
    40,723
    Juergen Heinzl
    Dec 14, 2003
  2. Will Rocisky
    Replies:
    7
    Views:
    342
    Mensanator
    Aug 9, 2008
  3. ma740988
    Replies:
    13
    Views:
    1,045
    James Kanze
    Dec 14, 2008
  4. Saraswati lakki
    Replies:
    0
    Views:
    1,287
    Saraswati lakki
    Jan 6, 2012
  5. Dermot Moynihan
    Replies:
    9
    Views:
    334
    Dermot Moynihan
    Jan 6, 2007
Loading...

Share This Page