Alternative coding for decimal arithmetic

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,'.')

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. [email protected]

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.

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
[email protected]

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 forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs