Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby decimal precision

Sorry if this is obvious, but I search Google, Stack Overflow, and the Ruby documentation and I couldn't find it.

How would I go about making a higher precision decimal? For example, in IRB,

irb(main):001:0> 3.14159265358979323846
=> 3.141592653589793

It cuts off some of the decimal. How do I keep the whole decimal?

like image 928
tckmn Avatar asked Aug 25 '26 09:08

tckmn


2 Answers

You need to use the BigDecimal class: http://www.ruby-doc.org/stdlib-1.9.3/libdoc/bigdecimal/rdoc/BigDecimal.html

BigDecimal provides arbitrary-precision floating point decimal arithmetic.

Example:

irb(main):009:0> BigDecimal.new("654.687465465496876516874651463549867651")
=> #<BigDecimal:2da6878,'0.6546874654 6549687651 6874651463 549867651E3',45(54)>
like image 65
SirDarius Avatar answered Aug 27 '26 00:08

SirDarius


Try this:

require 'bigdecimal/math'
include BigMath
puts PI(70) #You'll get a few more digits above 70, but those will be off. 70 is by no means the maximum.
#=> 0.314159265358979323846264338327950288419716939937510582097494459230781640628620899862802532985155833326733E1
like image 22
steenslag Avatar answered Aug 27 '26 00:08

steenslag



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!