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 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 **

3

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 e from **

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:

1e18 is a scientific notation meaning 1 * 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.

Share this article
Twitter Facebook Pinterest