Rounding to the nearest 0.05

P

Peter Roome

Hey guys.

Having difficulty figuring out where to begin with trying to round a
calculation to the nearest 0.05. Can anyone offer any suggestions
please?

Kind Regards

Pete
 
P

Phrogz

Having difficulty figuring out where to begin with trying to round a
calculation to the nearest 0.05. Can anyone offer any suggestions
please?

irb(main):016:0> 10.times{
irb(main):017:1* n = rand
irb(main):018:1> rounded = (n * 20).round / 20.0
irb(main):019:1> puts "%.02f" % rounded
irb(main):020:1> }
0.95
0.05
0.70
0.50
0.30
0.35
0.95
0.25
0.75
0.45
 
C

Coey Minear

Peter said:
Hey guys.

Having difficulty figuring out where to begin with trying to round a
calculation to the nearest 0.05. Can anyone offer any suggestions
please?

Kind Regards

Pete

Just off-hand, my initial reaction would be:

(a * 20).round.to_f/20

where "a" is your variable. Some quick tests with irb seems to show
this as working.

Coey
 
P

Peter Roome

Just off-hand, my initial reaction would be:
(a * 20).round.to_f/20

where "a" is your variable. Some quick tests with irb seems to show
this as working.

Coey

Cheers for the quick response guys, much appreciated. What difference
would the .to_f make between these solutions?
 
K

Konrad Meyer

--nextPart1250230.5gGxXYnGQu
Content-Type: text/plain;
charset="utf-8"
Content-Transfer-Encoding: quoted-printable
Content-Disposition: inline

Quoth Peter Roome:
=20
Cheers for the quick response guys, much appreciated. What difference
would the .to_f make between these solutions?
--=20
Posted via http://www.ruby-forum.com/.

One solution used (expr).to_f/20, the other used (expr)/20.0.
Both of these ensure floating point division is used instead of integer=20
division, that's all.

=2D-=20
Konrad Meyer <[email protected]> http://konrad.sobertillnoon.com/

--nextPart1250230.5gGxXYnGQu
Content-Type: application/pgp-signature; name=signature.asc
Content-Description: This is a digitally signed message part.

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.7 (GNU/Linux)

iD8DBQBHIkjLCHB0oCiR2cwRAnUUAJ4gq8/7rPgpiPsVOHaePg+ZQtVv4ACbBLvB
Oqz8l9veI8ZV85bS60VfsPA=
=w8/k
-----END PGP SIGNATURE-----

--nextPart1250230.5gGxXYnGQu--
 
P

Peter Roome

Konrad said:
Quoth Peter Roome:

One solution used (expr).to_f/20, the other used (expr)/20.0.
Both of these ensure floating point division is used instead of integer
division, that's all.

Ahhhh ok thanks for clearing that up!
 
Z

Zoltar Speaks

Just out of interest how did you get 20 as the number to multiply and
divide by?! Sorry its been a heavy week :-s
 

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

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top