On Sep 16, 2010, at 12:53 , Jeremy Evans wrote:
> If you really want to deal with percentage as a float, you should
> probably be using a double precision type in the database. You are
> probably using a decimal or numeric type in the database, and the only
> appropriate ruby type is BigDecimal, as Float does not support
> arbitrary precision (it has about 15 significant digits).
I don't really want to deal with it as a float. In the database, it's a
numeric(5,2) with a further constraint binding it to a value between 0.00 and
100.00. The annoying consequence has been that, unless I go out of my way to
apply formatting to it, it shows up in scientific notation.
I eventually ran across a number of numeric values whose default appearance was
rather stupid, and ended up creating the .to_ss method for the Numeric class. I
don't remember why I called it "to_ss", maybe I was thinking "to Stripped
String?"
Anyway, the result is:
>> b = BigDecimal.new("43")
=> #<BigDecimal:101ed46b0,'0.43E2',4(8)>
>> print "#{b} \t #{b.to_f} \t #{b.to_ss} \n"
0.43E2 43.0 43
.to_ss converts the number to a float-y string, eats all the blanks off the
front, eats all the zeros off the back, and then eats periods off the back,
which might have been exposed by the zero consumption. Since 98% of the
percentages in the database are whole numbers, including that ".0" on every one
is ridiculous. I'm sure I'll be rewriting some of the following code sometime
soon; already I'm wondering why the sprintf format is "6.3", for example.
class Numeric
def to_ss
sprintf("%6.3f",self).rcharstrip('0').rcharstrip('.').lcharstrip(' ')
end
end
(and why 'strip" doesn't accept a character parameter as the thing I want
stripped is also rather mysterious to me.)
class String
def rcharstrip(stripchar=nil)
if stripchar then
self.scan(/./).reverse.join.lcharstrip(stripchar).scan(/./).reverse.join
else
self.rstrip
end
end
def lcharstrip(stripchar=nil)
if stripchar then
index = 0
self.each_char do |char|
if char==stripchar then
index += 1
return "" unless index < (self.jlength)
else
break
end
end
return self.scan(/./)[index..-1].join
else
self.lstrip
end
end
end
--
You received this message because you are subscribed to the Google Groups
"sequel-talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/sequel-talk?hl=en.