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

def number_to_engineering(value, precision=3)
  expof10 = ((Math.log10(value)/3.0).floor)*3
  value *= 10**(-expof10)
  case 
    when value>=1000.0 : 
      value /= 1000.0
      expof10 +=3 
    when value>=100.0 :  precision -= 2 
    when value>=10.0 :  precision -= 1 
  end
  "%.*fe%d" % [precision-1, value, expof10]
end

number_to_engineering(15000) => "15e3"


Helper to format numbers using scientific notation

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

def number_to_scientific(num,precision=3)
	"%.#{precision}e" % num
end

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...)

def number_to_ordinal(num)
  num = num.to_i
  if (10...20)===num
    "#{num}th"
  else
    g = %w{ th st nd rd th th th th th th }
    a = num.to_s
    c=a[-1..-1].to_i
    a + g[c]
  end
end

number_to_ordinal(12) => "12th"
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.

def text_list(listtext,sep1=", ", sep2=", and ")
  n=listtext.size
  if n>1 : (listtext.first(n-1)).join(sep1) + sep2 +listtext.last 
  else listtext.first end
end

text_list(["cat", "dog", "bird"]) => "cat, dog, and bird"
« Newer Snippets
Older Snippets »
Showing 1-4 of 4 total  RSS