Search code examples
ruby-on-railsrubyscientific-notation

Ruby/Rails: How can I display a number in scientific notation?


I figured this would be an easy one, but I can't find any information about it anywhere. Lets say a user enters 123456. I want to display this in scientific notation. So that would be 1.23456 * 10^5. I figured ruby or rails would have a helper method, like scientific_notation(123456), but I can't find anything. Is this possible?

And to take it a step further, what about processing the number if the user enters scientific notation? For instance, they enter 1.23456x10^6 - rails parses this and stores 123456 in the database.

I realize the second part is a long shot.


Solution

  • To convert a number into power of e we can use the % operator.

    say x = 123456 then

    "%e" %x
    => 1.234560e+05