Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Controlling printing in scientific notation

Tags:

ruby

If I have an extremely long floating point number in Ruby such as:

 x = 123456789012345.to_f

when it is displayed, say, via to_s, it appears in scientific notation:

 "1.23456789012345e+14"

Is there any way to suppress the formatting in scientific notation, or on the other side of the coin, force it for extremely short floating point numbers?

like image 271
kmorris511 Avatar asked Jul 27 '09 17:07

kmorris511


People also ask

How do I stop R from printing in scientific notation?

If you want to avoid scientific notation for a given number or a series of numbers, you can use the format() function by passing scientific = FALSE as an argument.

How do you change a decimal into scientific notation?

Convert scientific notation to decimal formDetermine the exponent, n , on the factor 10 . Move the decimal n places, adding zeros if needed. If the exponent is positive, move the decimal point n places to the right. If the exponent is negative, move the decimal point |n| places to the left.

How do I change the scientific number format in R?

To set the use of scientific notation in your entire R session, you can use the scipen option. From the documentation ( ? options ): 'scipen': integer.

How do you convert numbers to scientific notation in C#?

decimal h = Convert. ToDecimal("2.09550901805872E-05"); decimal h2 = Decimal. Parse( "2.09550901805872E-05", System.


2 Answers

You can do all sorts of things using the % operator. For example:

x = 123456789012345.to_f
"%f" % x  # => "123456789012345.000000"

y = 1.23
"%E" % y # => "1.230000E+000"

The various options are the same as for the sprintf function.

like image 91
Pesto Avatar answered Oct 17 '22 14:10

Pesto


Just for convenience you can also control number of digits after decimal point. So do:

x = 1.234598
"%.3E" % x=> "1.235E+00"

Another neat thing you can do is pad with space from left like this:

x = 1.234 
"%10.3E" % x => " 1.234E+00" 
like image 32
Tomato Avatar answered Oct 17 '22 14:10

Tomato