Forum: Ruby on Rails Alternative coding for decimal arithmetic

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.
James B. (Guest)
on 2009-04-30 17:30
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,'.')
Colin L. (Guest)
on 2009-04-30 17:51
(Received via mailing list)
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 B. <removed_email_address@domain.invalid>
James B. (Guest)
on 2009-04-30 18:14
Colin L. wrote:
> Can't you just do something like
> (1/ (trate.to_f)).to_s
> I expect you don't need all the parantheses1

I cannot drop to floating point.  It has to be integer arithmetic.
Marnen L. (Guest)
on 2009-04-30 19:06
James B. 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
removed_email_address@domain.invalid
James B. (Guest)
on 2009-04-30 20:19
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 like

Thanks, that works much better.
This topic is locked and can not be replied to.