round the floating point to nearest halfpoint

L

Lucky Nl

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
 
R

Robert Klemme

2010/5/26 Lucky Nl said:
=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/
 

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. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top