Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 393
chrabyrd Avatar asked Nov 07 '25 20:11

chrabyrd


2 Answers

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.

like image 167
the Tin Man Avatar answered Nov 09 '25 10:11

the Tin Man


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 
like image 37
John La Rooy Avatar answered Nov 09 '25 09:11

John La Rooy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!