labelcd6
labelcd6

Reputation: 119

BigDecimal - Basic Calculations

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
  1. How do I convert 0.601E1 to 6.1 in BigDecimal?

  2. Where can I find some basic BigDecimal resources?

  3. Are there any other basic BigDecimal concepts that I should keep in mind?

Upvotes: 2

Views: 243

Answers (4)

Rok Kralj
Rok Kralj

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

Bala
Bala

Reputation: 11274

 (BigDecimal.new("2.33") + BigDecimal.new("3.68")).to_f

Upvotes: 0

sandymatt
sandymatt

Reputation: 5612

  1. Have a look at this method

  2. There are a handful of good examples inlined in the docs themselves, illustrating how to use some of the different calls.

  3. 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

Arup Rakshit
Arup Rakshit

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

Related Questions