[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

truncate float to 2 decimals

Junkone

8/13/2008 3:49:00 PM

how do i truncate the float to 2 decimals

irb(#<Object:0x3d95578>):001:0> f=0.911501706632285
=> 0.911501706632285

5 Answers

ara.t.howard

8/13/2008 3:58:00 PM

0


On Aug 13, 2008, at 9:47 AM, Junkone wrote:

> how do i truncate the float to 2 decimals
>
> irb(#<Object:0x3d95578>):001:0> f=0.911501706632285
> => 0.911501706632285

just use the normal math way

cfp:~ > cat a.rb
float = 0.911501706632285

puts( Integer(float * 100) / Float(100) )


cfp:~ > ruby a.rb
0.91




a @ http://codeforp...
--
we can deny everything, except that we have the possibility of being
better. simply reflect on that.
h.h. the 14th dalai lama




Tim Hunter

8/13/2008 3:59:00 PM

0

Junkone wrote:
> how do i truncate the float to 2 decimals
>
> irb(#<Object:0x3d95578>):001:0> f=0.911501706632285
> => 0.911501706632285

Do you really want to change f?

f2 = (f*100).to_i / 100.0

Or do you just want to display f with 2 decimals?

"%5.2f" % f
--
Posted via http://www.ruby-....

James Gray

8/13/2008 4:06:00 PM

0

On Aug 13, 2008, at 10:47 AM, Junkone wrote:

> how do i truncate the float to 2 decimals
>
> irb(#<Object:0x3d95578>):001:0> f=0.911501706632285
> => 0.911501706632285

>> "%0.2f" % 0.911501706632285
=> "0.91"

James Edward Gray II

Trans

8/13/2008 6:52:00 PM

0

With Facets:

require 'facets/float/round'

f=0.911501706632285

f.round_at(2)

or

f.round_to(.01)

Also, Ruby 1.9 modifies #round to take a decimal place, I believe.

T.

Tom Reilly

8/14/2008 8:47:00 PM

0

You might also try :
puts (((float * 100.0).round / 100.0).to_i)

ara.t.howard wrote:
>
> On Aug 13, 2008, at 9:47 AM, Junkone wrote:
>
>> how do i truncate the float to 2 decimals
>>
>> irb(#<Object:0x3d95578>):001:0> f=0.911501706632285
>> => 0.911501706632285
>
> just use the normal math way
>
> cfp:~ > cat a.rb
> float = 0.911501706632285
>
> puts( Integer(float * 100) / Float(100) )
>
>
> cfp:~ > ruby a.rb
> 0.91
>
>
>
>
> a @ http://codeforp...
> --
> we can deny everything, except that we have the possibility of being
> better. simply reflect on that.
> h.h. the 14th dalai lama
>
>
>
>
>