Reputation: 16202
Somehow I can't find the answer to this using google or SO...
Consider:
require 'bigdecimal'
puts (BigDecimal.new(1)/BigDecimal.new(3)).to_s
#=> 0.333333333333333333E0
I want the ability to specify a precision of 100 or 200 or 1000, which would print out "0." followed by 100 threes, 200 threes, or 1000 threes, respectively.
How can I accomplish this? The answer should also work for non-repeating decimals, in which case the extra digits of precision of would be filled with zeros.
Thanks!
Upvotes: 1
Views: 173
Reputation: 1248
I think the problem is that the BigDecimal
objects don't have their precision set to a value high enough. I can get a 1000 fractional digits printed if I explicitly specify the required precision of the operation by using div
instead of /
:
require 'bigdecimal'
puts (BigDecimal.new(1).div(BigDecimal.new(3), 1000)).to_s
#=> 0.3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333E0
After that, you can limit the number of fractional digits with round
.
Upvotes: 5