Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Kevin

« Newer Snippets
Older Snippets »
Showing 1-4 of 4 total  RSS 

Number to Engineering format

Engineering format lists the exponent in powers of three

   1  
   2  def number_to_engineering(value, precision=3)
   3    expof10 = ((Math.log10(value)/3.0).floor)*3
   4    value *= 10**(-expof10)
   5    case 
   6      when value>=1000.0 : 
   7        value /= 1000.0
   8        expof10 +=3 
   9      when value>=100.0 :  precision -= 2 
  10      when value>=10.0 :  precision -= 1 
  11    end
  12    "%.*fe%d" % [precision-1, value, expof10]
  13  end
  14  
  15  number_to_engineering(15000) => "15e3"


Helper to format numbers using scientific notation

For those of us who can't remember the formatting codes

   1  
   2  def number_to_scientific(num,precision=3)
   3  	"%.#{precision}e" % num
   4  end
   5  
   6  number_to_scientific(10000) => 1.000e004

in some cases it might be better to use the 'g' code instead of the 'e' code.

Helper to print numbers as ordinals (1st, 2nd, 3rd...)

   1  
   2  def number_to_ordinal(num)
   3    num = num.to_i
   4    if (10...20)===num
   5      "#{num}th"
   6    else
   7      g = %w{ th st nd rd th th th th th th }
   8      a = num.to_s
   9      c=a[-1..-1].to_i
  10      a + g[c]
  11    end
  12  end
  13  
  14  number_to_ordinal(12) => "12th"
  15  number_to_ordinal(7) => "7th"


Note that floats will be converted to ints (without rounding) before processing.

Write out an array as a list with commas and an 'and'

Actually, you can customize the separators to your needs.

   1  
   2  def text_list(listtext,sep1=", ", sep2=", and ")
   3    n=listtext.size
   4    if n>1 : (listtext.first(n-1)).join(sep1) + sep2 +listtext.last 
   5    else listtext.first end
   6  end
   7  
   8  text_list(["cat", "dog", "bird"]) => "cat, dog, and bird"
« Newer Snippets
Older Snippets »
Showing 1-4 of 4 total  RSS