hello all
i was lookin for a method which wud print the floating numbers
without fractional part if the fractional part is 0
5.0 shud print 5
5.5 shud print 5.5
is there any helper method to do it
jags
hello all
i was lookin for a method which wud print the floating numbers
without fractional part if the fractional part is 0
5.0 shud print 5
5.5 shud print 5.5
is there any helper method to do it
jags
What about using a helper method:
def my_special_float_format(val=0.0)
val % 1 == 0 ? val.to_i : val
end
On Tue, May 6, 2008 at 6:03 AM, Jags R.
[email protected]
wrote:
jags
Posted via http://www.ruby-forum.com/.
–
James M.
Hi James
Thanx for that
further on this suppose the method name is sff(special float format)
how will i able to do such statement
anyfloatvalue.to_spp
like we do
anyfloatvalue.to_i
i dont want to pass argument
thanks again
James M. wrote:
What about using a helper method:
def my_special_float_format(val=0.0)
val % 1 == 0 ? val.to_i : val
endOn Tue, May 6, 2008 at 6:03 AM, Jags R.
[email protected]
wrote:jags
Posted via http://www.ruby-forum.com/.
–
James M.
I’d probably go with something a bit more specific to a float:
def to_spp(num)
raise ArgumentError unless num.respond_to?(:floor)
num.floor==num ? num.to_i.to_s : num.to_s
end
Personally I would recommend putting this in application_helper.rb and
using it like the ‘number_to_currency’ helper because it appears to be
something that you only want to do when rendering the value in a
view.
If you want to use it as an instance method on float (as you suggest)
then it’s fairly straightforward. Ruby classes are always open for
extension so you just open the class and add it. Often extensions to
core classes are put in /lib/core_ext with a file name similar to the
class your extending. In this case you might have the following in /
lib/core_ext/float_ext.rb
class Float
def to_spp
num.floor==num ? num.to_i.to_s : num.to_s
end
end
Then in your environment.rb you’d require ‘core_ext/float_ext’ (it’ll
search and find the path under lib) and you could simply invoke it on
your floats.
wow! cool!
thanks andy thats all i needed.got some ruby insight in the process
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