On Sat, May 16, 2009 at 1:57 AM, Max Williams <toastkid.williams / gmail.com> wrote: > I have a requirement where i need to display (ie convert to a string) > all digits to 3 significant figures. (not the same as 3 decimal places) > > eg > > 23 => "23" > 26759 => "26,800" > 10.546 => "10.5" > 3332332 => "3,330,000" > 0.766 => "0.766" > 0.00000766 => "0.00000766" > > Can anyone show me a neat way to do this? I'd have thought that there'd > be a method for it already but i can't find one. > > thanks! > max > -- > Posted via http://www.ruby-forum.com/. > > Sorry, but I don't have much time that I can spend to come up with a better answer right now. But, I thought I would throw this idea your way. Check it carefully (it may have bugs) and maybe you can make improvements. require 'bigdecimal' arr = [23,26759,10.546,3332332,0.766,0.00000766] arr.each do |x| m = 2 - Math.log10(x).floor p BigDecimal.new(((x*10**m).round*10**(-1*m)).to_s).to_s('F').gsub(/\.0*$/,"") end #output ########## #> "23" #> "26800" #> "10.5" #> "3330000" #> "0.766" #> "0.00000766" Harry -- A Look into Japanese Ruby List in English http://www.kakueki.com/ruby/list.html