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

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

On Oct 26, 1:19 pm, Peter R. [email protected] wrote:

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

Peter R. writes:

Hey guys.

calculation to the nearest 0.05. Can anyone offer any suggestions

please?Kind Regards

## Pete

Posted via http://www.ruby-forum.com/.

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

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?

Quoth Peter R.:

## would the .to_f make between these solutions?

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

division, that’s all.

Konrad M. wrote:

Quoth Peter R.:

## would the .to_f make between these solutions?

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

division, that’s all.

Ahhhh ok thanks for clearing that up!

On Oct 26, 2:48 pm, Zoltar S. [email protected] wrote:

Just out of interest how did you get 20 as the number to multiply and

divide by?! Sorry its been a heavy week :-s

1 / 0.05 #=> 20

Gavin K. wrote:

On Oct 26, 2:48 pm, Zoltar S. [email protected] wrote:

Just out of interest how did you get 20 as the number to multiply and

divide by?! Sorry its been a heavy week :-s1 / 0.05 #=> 20

Ace cheers!

divide by?! Sorry its been a heavy week :-s

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs