Advertisement
dkh503

dec2Eng.lua

Apr 5th, 2019
241
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.45 KB | None | 0 0
  1. -- scriptName: dec2Eng
  2. -- by: dkh503@gmail.com
  3.  
  4. -- Enter a number and get the Engineering Notation.
  5.  
  6. function dec2Eng(x)
  7.     assert(tonumber(x), "Error: invalid entry.")
  8.     y = 0
  9.  
  10.     while x >= 1 do
  11.         x = x / 10
  12.         y = y + 1
  13.     end
  14.     while x < 1 do
  15.         x = x * 10
  16.         y = y - 1
  17.     end
  18.  
  19.     if (y % 3) == 1 then
  20.         y = y - 1
  21.         x = x * 10
  22.     elseif (y % 3) == 2 then
  23.         y = y + 1
  24.         x = x / 10
  25.     end
  26.  
  27.     if x < 1 then
  28.         x = x * 1000
  29.         y = y - 3
  30.     end
  31.  
  32.     return string.format("%.3fe%d", x, y)
  33. end
  34.  
  35. io.write(
  36. [[----------------------------------
  37.  ** dec2Eng.lua **
  38. Converts decimal, hex or
  39. scientific notation entries to
  40. Engineering Notation
  41. ----------------------------------]])
  42.  
  43. io.write("\nEnter a number      : ")
  44. z = dec2Eng(io.read("*n"))
  45.  
  46. io.write(string.format("Engineering Notation: %s\n\n", z))
  47.  
  48.  
  49.  
  50. -- Engineering notation:
  51. -- 1. Uses exponents in multiples of 3 only.
  52. -- 2. 0 < Base <1000
  53.  
  54. -- This matches up with "Metric Prefixes" like milli[amps],
  55. -- micro[meters], and nano[farads] (negative exponents);
  56. -- and kilo[ohms], mega[hertz], and giga[bytes] (positive exponents),
  57. -- often seen in electronic and engineering measurements.
  58.  
  59. --[[https://en.wikipedia.org/wiki/Metric_prefix
  60.  
  61.     Tera    T   1000000000000   10e12
  62.     Giga    G   1000000000  10e9
  63.     Mega    M   1000000     10e6
  64.     Kilo    K   1000        10e3
  65.     (none)  (none)  1       10e0
  66.     milli   m   0.001       10e-3
  67.     micro   ยต  0.000001    10e-6
  68.     nano    n   0.000000001     10e-9
  69.     pico    p   0.000000000001  10e-12
  70.  
  71. --]]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement