Reputation: 119
require 'bigdecimal'
sum = BigDecimal.new("2.33")
sum1 = BigDecimal.new("3.68")
sum2 = sum + sum1
puts sum2
# 0.601E1
# my attempt at converting scientific notation
puts sum2.to_i
# 6
How do I convert 0.601E1
to 6.1
in BigDecimal
?
Where can I find some basic BigDecimal
resources?
Are there any other basic BigDecimal
concepts that I should keep in mind?
Upvotes: 2
Views: 243
Reputation: 48775
1) You have to call #to_s
with paramter 'F'
.
sum2.to_s('F')
The solutions others have given you are not great, if you convert BigDecimal to the immediate float, you lose precision.
2) Ruby documentation is pretty good.
3) The important concept is: Do not convert immediate results you calculate using BigDecimal to Float (which is IEE floating point). You are going to destroy all the effort this way. This is such a simple concept to grasp, yet a lot of people fail to.
Upvotes: 2
Reputation: 5612
Have a look at this method
There are a handful of good examples inlined in the docs themselves, illustrating how to use some of the different calls.
Once again, the docs have a bunch of good info -- one to keep in mind is that it's possible to have both positive and negative zeroes
Sorry, I realize everything here points to the docs, but it's honestly the first place I look when I'm looking for answers.
Upvotes: 0
Reputation: 118289
Here is one try using BigDecimal#to_f
:
require 'bigdecimal'
sum = BigDecimal.new("2.33")
sum1 = BigDecimal.new("3.68")
sum2 = sum + sum1
puts sum2.to_f
# >> 6.01
Upvotes: -1