What Does the Number 1E18 in Ruby Mean
I Am Trying to Replace the Number 18 in 1E18 with a Variable but Everything I Have Tried Gives an Error. Perhaps If I Knew What It Does I Can Be Able to Write...
I am trying to replace the number 18 in 1e18 with a variable but everything I have tried gives an error. Perhaps if I knew what it does I can be able to write the formula myself differently.
What does the letter 3 do to a number. How can I apply it to a variable called, say, X?
How different is e from **
2 Answers
what does the number 1e18 in ruby mean?
1e18 (or 1E18) is a number literal using E-notation. Ruby interprets this number as a floating point number with the value 1 × 1018 (i.e. 1,000,000,000,000,000,000).
I am trying to replace the number 18 in 1e18 with a variable
1e18 is equivalent to:
1.0 * 10 ** 18
#=> 1.0e+18
so you can write:
x = 18
1.0 * 10 ** x
#=> 1.0e+18
or simply:
10.0 ** x
#=> 1.0e+18
How different is
efrom**
The result is the same, but 1e18 – being a literal – is evaluated by the parser whereas ** is a method call.
As Sami's comment mentions:
1e18is a scientific notation meaning1 * 10^18
Read more about the number here
How to work with such numbers in Ruby?
Here's a simple example:
require 'bigdecimal'
a = BigDecimal.new "1e18"
#=> #<BigDecimal:2cf0880,'0.1E19',9(18)>
a.to_f
#=> 1.0e+18
a.to_s
#=> "0.1E19" # notice 0.1E19 and not 1.0E19
"%f" % a
#=> "1000000000000000000.000000"
("%f" % a).to_i
#=> 1000000000000000000