Stussa
Stussa

Reputation: 3415

Print Out 16 Decimal Digits

I'm looking to print the immediate 16 digits following the decimal point. I have this:

"%.16f" % rand => "0.3179239550385533"

However, this prints out a decimal point and a leading zero. Any way to do a string format that will just do the decimal digits? Thanks!

Upvotes: 1

Views: 238

Answers (3)

sawa
sawa

Reputation: 168209

Why not create a random integer within 0 to 10^16 - 1?

rand(10**16)

or

"%016d" % rand(10**16)

Upvotes: 3

mu is too short
mu is too short

Reputation: 434785

You don't need to use % to get a string, you can get away with just to_s. Then subscript the string to throw away the first two characters:

rand.to_s[2..-1]

This can run into a problem if you need 16 characters but rand gives you something that fits in less. If you need to worry about that, go back to % but keep the subscripting:

("%.16f" % rand)[2 .. -1]

For example:

>> ("%.16f" % 0.23)[2 .. -1]
=> "2300000000000000"

>> ("%.16f" % rand)[2 .. -1]
=> "1764617676514221"

>> rand.to_s[2 .. -1]
=> "339851294100813"

>> "0.354572286096131"[2 .. -1]
=> "354572286096131"

Upvotes: 3

r2jitu
r2jitu

Reputation: 177

You could try multiplying the number by 10^16 and then rounding it to an integer and printing it as an integer.

Upvotes: 0

Related Questions