From: Rob Biedenharn Date: 2009-05-16T02:45:59+09:00 Subject: Re: Rounding any number (int or float) to 3 significant figures On May 15, 2009, at 12:57 PM, Max Williams 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 > -- This should get you started: irb> h.each do |n,s| irb> puts( ("%f"%[("%.3g"%n).to_f]).sub(/\.?0*\z/,'') ) irb> end 0.766 23 26800 10.5 3330000 0.000008 => {0.766=>"0.766", 23=>"23", 26759=>"26,800", 10.546=>"10.5", 3332332=>"3,330,000", 7.66e-06=>"0.00000766"} It doesn't do so well with the smallest value, but if you know the ranges you're dealing with, perhaps you can adjust the %f spec. -Rob Rob Biedenharn http://agileconsultingllc.com Rob@AgileConsultingLLC.com