fork(1) download
  1. class String
  2. def to_sci
  3. num = self
  4. num += '.0' unless num.include?('.')
  5. negative = num.slice!(0) if num[0] == '-'
  6. negative ||= false
  7. num.prepend('0') if num[0] == '.'
  8. raise "Must be a non-zero number I can turn into scientific notation" unless num.delete('1234567890-') == '.' && num =~ /\A(0[\.].*[1-9]|[1-9])/
  9. e = num.match(/((?<=0[\.])0*[1-9]|(?<=[1-9])\d*(?=[\.]))/)[0].length.to_s
  10. simple = num.delete('.').scan(/[1-9]\d*(?=0*)/)[0].insert(1,'.')
  11. simple.prepend('-') if negative #if the number's negative, add the proper sign
  12. e.prepend('-') if num =~ /\A-?0/ #it's negative sci-notation, so add a sign =)
  13. return "#{simple} x 10^#{e}"
  14. end
  15. end
  16. input = ''
  17. num = (rand(1509290) / rand(100).to_f).to_s
  18. num = input if input != ''
  19. puts "#{num}: #{num.to_sci}"
Success #stdin #stdout 0s 4716KB
stdin
Standard input is empty
stdout
11609.938461538462: 1.1609938461538462 x 10^4