DZone 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

Snippets has posted 5883 posts at DZone. View Full User Profile

Number To Engineering Format

08.23.2005
| 6216 views |
  • submit to reddit
        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"