Alternative coding for decimal arithmetic


#1

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

#2

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


#3

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.


#4

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


#5

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.