If I do
require "bigdecimal"
"`.50f" % [BigDecimal("1") / BigDecimal("3")]
=> " 0.33333333333333331482961625624739099293947219848633"
Is it possible to print out the result to any length with all 3
s at the end? (That is 0.333333333333...
to any length?)
CodePudding user response:
You are observing a loss of precision there because you are formatting the BigDecimal
object to a Float first (because of your f
format flag) which can't represent arbitrary precision floating point numbers.
However, you can use BigDecimal#to_s
to format a Bigdecimal
object as a string without any loss of precision. Here, the output will use as much precision as is available in the object you are formatting.
When creating your object with BigDecimal#/
, it will use some predefined precision, on my box this was 36
on Ruby 3.1. This will result in 36 decimal numbers being printed by default:
result = BigDecimal("1") / BigDecimal("3")
result.precision
# => 36
result.to_s('F')
# => "0.333333333333333333333333333333333333"
If you desire higher precision in the resulting BigDecimal object after your division, you can use BigDecimal#quo
instead:
result = BigDecimal("1").quo(BigDecimal("3"), 60)
result.precision
# => 60
result.to_s('F')
# => "0.333333333333333333333333333333333333333333333333333333333333"