Feature #8850

Convert Rational to decimal string

Added by Yui NARUSE 8 months ago. Updated 2 months ago.

[ruby-core:56955]
Status:Assigned
Priority:Normal
Assignee:Yukihiro Matsumoto
Category:-
Target version:next minor

Description

On Ruby 2.1.0, decimal literal is introduced.
It generates Rational but it cannot easily convert to decimal string.
You know, Rational#tof is related to this but
* Float is not exact number
** 0.123456789123456789r.to
f.tos #=> "0.12345678912345678"
* it can't handle recursive decimal
** (151/13r).to
f.to_s #=> "11.615384615384615"

  • the method name ** todecimal ** todecimalstring ** tos(format: :decimal) ** extend sprintf
  • how does it express recursive decimal ** (151/13r).todecimalstring #=> "11.615384..." ** (151/13r).todecimalstring #=> "11.(615384)"

Example implementation is following.
Its result is
** 0.123456789123456789r.tof.tos #=> "0.123456789123456789"
** (151/13r).tof.tos #=> "11.(615384)"

class Rational
  def to_decimal_string(base=10)
    n = numerator
    d = denominator
    r, n = n.divmod d
    str = r.to_s(base)
    return str if n == 0
    h = {}
    str << '.'
    n *= base
    str.size.upto(Float::INFINITY) do |i|
      r, n = n.divmod d
      if n == 0
        str << r.to_s(base)
        break
      elsif h.key? n
        str[h[n], 0] = '('
        str << ')'
        break
      else
        str << r.to_s(base)
        h[n] = i
        n *= base
      end
    end
    str
  end
end

History

#1 Updated by Boris Stitnicky 8 months ago

How about to_s( :decimal ) ?

#2 Updated by Nobuyoshi Nakada 2 months ago

  • Description updated (diff)

#3 Updated by Shyouhei Urabe 2 months ago

  • Status changed from Assigned to Feedback

Can anyone propose a patch please?

#5 Updated by Kenta Murata 2 months ago

  • Status changed from Feedback to Assigned

Also available in: Atom PDF