tckmn
tckmn

Reputation: 59343

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?

Upvotes: 3

Views: 785

Answers (2)

steenslag
steenslag

Reputation: 80085

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

Upvotes: 1

SirDarius
SirDarius

Reputation: 42969

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)>

Upvotes: 3

Related Questions