I need to transform a decimal fraction received as a string into its reciprocal, also stored as a string. I have come up with this but I would like to know if there exists a better way to accomplish this requirement. trate = xchg.xpath(''cb:value'').text scale = 10 ** (trate.length() -1 - (trate.index(''.'').to_i)) value = trate.gsub(/\.|,| /,'''').to_i trate = (1000000 * scale / value).to_s trate = trate.rjust(7,''0'') trate = trate.insert(-7,''.'') -- Posted via http://www.ruby-forum.com/.
Can''t you just do something like (1/ (trate.to_f)).to_s I expect you don''t need all the parantheses1 2009/4/30 James Byrne <rails-mailing-list-ARtvInVfO7ksV2N9l4h3zg@public.gmane.org>> > I need to transform a decimal fraction received as a string into its > reciprocal, also stored as a string. I have come up with this but I > would like to know if there exists a better way to accomplish this > requirement. > > trate = xchg.xpath(''cb:value'').text > scale = 10 ** (trate.length() -1 - (trate.index(''.'').to_i)) > value = trate.gsub(/\.|,| /,'''').to_i > trate = (1000000 * scale / value).to_s > trate = trate.rjust(7,''0'') > trate = trate.insert(-7,''.'') > -- > Posted via http://www.ruby-forum.com/. > > > >--~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en -~----------~----~----~----~------~----~------~--~---
Colin Law wrote:> Can''t you just do something like > (1/ (trate.to_f)).to_s > I expect you don''t need all the parantheses1I cannot drop to floating point. It has to be integer arithmetic. -- Posted via http://www.ruby-forum.com/.
James Byrne wrote:> > I cannot drop to floating point. It has to be integer arithmetic.Use BigDecimal (part of the standard library). It does arbitrary-precision decimal arithmetic without the problems of floats. I think the syntax would be something like (BigDecimal.new(1) / BigDecimal.new(trate)).to_s But check the docs to be sure. There''s certainly no need to jump through the hoops you''re going through right now. Best, -- Marnen Laibow-Koser http://www.marnen.org marnen-sbuyVjPbboAdnm+yROfE0A@public.gmane.org -- Posted via http://www.ruby-forum.com/.
Marnen Laibow-Koser wrote:> Use BigDecimal (part of the standard library). It does > arbitrary-precision decimal arithmetic without the problems of floats. > I think the syntax would be something likeThanks, that works much better. -- Posted via http://www.ruby-forum.com/.