chrabyrd
chrabyrd

Reputation: 323

How to get ruby to show more decimal places?

I'm currently doing a project Euler problem that requires me to find patterns in repeating decimals. However, Ruby rounds too soon and I can't find a way to flesh out decimals to the nth place.

For instance:

1/7.to_f => 0.14285714285714285

but I'm trying to make it so:

1/7.to_f => 0.14285714285714285714285714285757142857142857

Any help would be greatly appreciated!

Upvotes: 4

Views: 1182

Answers (2)

John La Rooy
John La Rooy

Reputation: 304355

You can easily get as many repeating digits as you like, by scaling up the computation by a power of 10

10**100/7
=> 1428571428571428571428571428571428571428571428571428571428571428571428571428571428571428571428571428 

Upvotes: 2

the Tin Man
the Tin Man

Reputation: 160571

All languages support being able to define the precision of floating point in output. Ruby uses the common format strings:

pi = 355.0/113.0
'%1.5f' % pi # => "3.14159"

Or, in your case:

'%1.20f' % (1.0/7.0) # => "0.14285714285714284921"
'%1.20f' % (1.to_f/7) # => "0.14285714285714284921"
'%1.20f' % (1/7.to_f) # => "0.14285714285714284921"

I'd recommend reading the documentation for String's % and Kernel::sprintf. How Ruby determines to use fixed or floating math and the uses of to_f is covered in any decent Ruby tutorial.

Upvotes: 3

Related Questions