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!
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"
Why not create a random integer within 0 to 10^16 - 1?
rand(10**16)
or
"%016d" % rand(10**16)
You could try multiplying the number by 10^16 and then rounding it to an integer and printing it as an integer.
精彩评论