This week only. Pastebin PRO Accounts Christmas Special! Don't miss out!Want more features on Pastebin? Sign Up, it's FREE!
Guest

scientific notation

By: a guest on Oct 29th, 2012  |  syntax: Ruby  |  size: 1.99 KB  |  views: 71  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. def shift(num,exp)
  2.   num = num.split(//)
  3.   if exp < 0
  4.     dotpos = 0
  5.     num.each_with_index do
  6.       |k,v| dotpos = v if k == "."
  7.     end
  8.     if exp.abs > dotpos
  9.       (exp.abs - dotpos).times do
  10.         num.insert(0,"0")
  11.       end
  12.       num.delete_if {|x| x == "."}
  13.       num.insert(0,".")
  14.     else
  15.      
  16.       num.delete_if {|x| x == "."}
  17.       num.insert(dotpos - exp.abs,".")
  18.     end
  19.   else
  20.     dotpos = 0
  21.     num.each_with_index do
  22.       |k,v| dotpos = v+1 if k == "."
  23.     end
  24.     exlen = num.length-dotpos
  25.     num.delete_if {|x| x == "."}
  26.     (exp-exlen).times do
  27.       num.insert((num.length),0)
  28.     end
  29.   end
  30.   num.join()
  31. end
  32.  
  33. def to_float(num)
  34.   num = num.split(//)
  35.   orignum,exp = "",""
  36.   endex,startex = 0,0
  37.   num.each_with_index {|k,v| endex = v and break if k == "x" or k == " "}
  38.   num.each_with_index {|k,v| startex = v and break if k == "^"}
  39.   num.each_with_index {|k,v| orignum << k if v < endex }
  40.   num.each_with_index {|k,v| exp << k if v > startex}
  41.   return 10 ** exp.to_i if orignum == "1"
  42.   return shift(orignum,exp.to_i)
  43. end
  44.  
  45. def to_sci(num)
  46.   num = num.to_s.split(//)
  47.   if num.join.to_f > 1
  48.     orignum,explen = "",0
  49.     startget = false
  50.     num.reverse.each {|x| startget = true if x != "0"; orignum << x if startget}
  51.     orignum = orignum.reverse
  52.     orignum = orignum.split(//).insert(1,".").join()
  53.     return orignum << " x 10^" << (num.length-1).to_s
  54.   else
  55.     return num.to_s << " x 10^0"  if num.join().to_f == 1.0
  56.     dotpos,fnumpos,explen = 0,0,0
  57.     orignum = ""
  58.     num.each_with_index {|k,v| dotpos = v if k == "."}
  59.     num.each_with_index do |k,v|
  60.       if k != "0" and k != "."
  61.         fnumpos = v
  62.         break
  63.       end
  64.     end
  65.     num.each_with_index {|k,v| orignum << k if v >= fnumpos}
  66.     orignum = orignum.split(//).insert(1,".").join()
  67.     num.each_with_index {|k,v| explen += 1 if dotpos < v and v <= fnumpos}
  68.     return orignum << " x 10^" << (explen*-1).to_s
  69.   end
  70. end
  71.  
  72. puts to_sci("632194030000")
  73. puts to_float("6.3219403 x 10^11")
clone this paste RAW Paste Data