On Sat, May 8, 2010 at 7:24 PM, RichardOnRails
<richarddummymailbox58...@uscomputergurus.com> wrote:
> Hi,
>
> I'm on a mission to show my granddaughter how Pi can be computed.  For
> that, I need Sqrt(2) computed accurately, which I've done.  But I need
> to display results in 5-digit groups, space separated.
>
> The following aims at displaying the five-or-less decimal components
> of a 12-decimal-digit number (related to sqrt(2) but ignoring scaling
> and precision for the moment).
>
> bd = BigDecimal("0.141421356237")
> group_sz=5
> re_string = "\\.(\\d{1," + group_sz.to_s + "})+"
> r = Regexp.new(re_string)
> m = r.match(bd.to_s)
> (0..3). each do |i|
>  puts( "%s => %s; m[%d] => %s"  %  [r,  m, i, m[i]] )
>
> I get (ignoring scaling for the moment):
>
> (?-mix:\.(\d{1,5})+) => .141421356237; m[0] => .141421356237
> (?-mix:\.(\d{1,5})+) => .141421356237; m[1] => 37  # want 14142
> (?-mix:\.(\d{1,5})+) => .141421356237; m[2] =>      # want 13562
> (?-mix:\.(\d{1,5})+) => .141421356237; m[3] =>      # want 37
>
> So the extra set of parentheses I added don't capture the way I want
> them to.  I can do it using Ruby to generate a bunch of consecutive
> \d{1,5} groups to satisfy my requirement,  but some insightful Regexp
> markup is preferable.
>
> Any ideas?

Does this help?

BigDecimal("0.141421356237").to_s.scan(/(\d{1,5}|\.|\E)/).join(" ")
#=> "0 . 14142 13562 37 E 0"

-- 
Rick DeNatale

Blog: http://talklikeaduck.denhaven2.com/
Github: http://github.com/rubyredrick
Twitter: @RickDeNatale
WWR: http://www.workingwithrails.com/person/9021-rick-denatale
LinkedIn: http://www.linkedin.com/in/rickdenatale

-- 
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-t...@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to