Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Ruby > round the floating point to nearest halfpoint

Reply
Thread Tools

round the floating point to nearest halfpoint

 
 
Lucky Nl
Guest
Posts: n/a
 
      05-26-2010
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/.

 
Reply With Quote
 
 
 
 
Robert Klemme
Guest
Posts: n/a
 
      05-26-2010
2010/5/26 Lucky Nl <(E-Mail Removed)>:
> =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/

 
Reply With Quote
 
 
 
 
Benoit Daloze
Guest
Posts: n/a
 
      05-26-2010
On 26 May 2010 15:09, Robert Klemme <(E-Mail Removed)> wrote:
>
> robert
>

Arf, you answered before I did finish my answer.

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

Regards,
B.D.

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
How to round a floating point to nearest 10? Will Rocisky Python 7 08-09-2008 10:38 PM
How to Round a float to an nearest whole number Don Java 30 03-04-2007 08:23 AM
round() to nearest .05 ? tertius Python 4 11-16-2004 10:58 AM
round number to nearest integer. Fred Java 3 06-06-2004 06:20 AM
round up to nearest number and significant figures Steve Java 5 05-17-2004 01:30 AM



Advertisments