Forum: Ruby on Rails pls help me regarding Maths round up function.....

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Prashant T. (Guest)
on 2006-06-06 12:04
Hi,

I have some values on my webpage displaying like
1.22333333333
2.33333344444
2.33377777777
etc.
Here I want to display values upto 2 decimal places correct.
i.e, 1.22333333333 should be dislayed as 1.22
     2.33333344444 should be dislayed as 2.33
     2.33777777777 should be dislayed as 2.34
& so on....

How to do this in ruby?????

Is there any function???

Thanx in advance.
Prash
ã?¹ã?¿ã?³ ã??ã?ºã?¬ã??ã?¯ (Guest)
on 2006-06-06 12:14
(Received via mailing list)
Hi.

(value*100).round/100.0

Stan
David B. (Guest)
on 2006-06-06 18:54
(Received via mailing list)
On 6/6/06, Prashant T. <removed_email_address@domain.invalid> wrote:
>      2.33777777777 should be dislayed as 2.34
> & so on....
>
> How to do this in ruby?????
>
> Is there any function???

puts "%.2f" % 223.3234235235 # =>223.32
Alex W. (Guest)
on 2006-06-07 00:03
Prashant T. wrote:
> Hi,
>
> I have some values on my webpage displaying like
> 1.22333333333
> 2.33333344444
> 2.33377777777
> etc.
> Here I want to display values upto 2 decimal places correct.
> i.e, 1.22333333333 should be dislayed as 1.22
>      2.33333344444 should be dislayed as 2.33
>      2.33777777777 should be dislayed as 2.34
> & so on....
>
> How to do this in ruby?????
>
> Is there any function???
>
> Thanx in advance.
> Prash

The most elegant way is facets/round_at

Check out http://facets.rubyforge.org/doc/api/
Specifically
http://facets.rubyforge.org/doc/api/classes/Float....

  require facet/round_at
  4.55555.round_at(2)    #=> 4.56
Jodi S. (Guest)
on 2006-06-07 15:58
(Received via mailing list)
>>
>> Is there any function???
>
> puts "%.2f" % 223.3234235235 # =>223.32

Hey Prash, this will round to a specific number of decimal pts:

	def round_float(float_num,dec)
		(float_num*(10**dec)).round.to_f / (10**dec).to_f
	end

	round_float(1.238, 2) => 1.24

cheers,
Jodi
This topic is locked and can not be replied to.