简体   繁体   中英

ruby 1.9.3-p194 rails 3.2.9 BigDecimal to_f always outputs 0.0

Since about last week, my usually working rails project started behaving badly in regards to BigDecimal.to_f. Every BigDecimal number gets output as 0.0 when calling to_f:

~/development/rails_project> rails c
Loading development environment (Rails 3.2.9)
1.9.3p194 :001 > BigDecimal.new('5').to_f
 => 0.0 

I'm running Ruby 1.9.3 patch level 194, and Rails 3.2.9, as I always have. Some co-workers who also work on the same project using the same versions don't have this issue.

Also tried with Ruby 1.9.3 patch level 362 with the same results. Has anyone had the same problem and knows how to overcome it?

Thanks.

EDIT:

My problem is not with the to_s function, but the to_f. I probably over-simplified, because my issue is with number_to_currency:

~/development/rails_project> rails c
Loading development environment (Rails 3.2.9)
1.9.3p194 :001 > include ActionView::Helpers::NumberHelper
 => Object 
1.9.3p194 :002 > BigDecimal.new('5').to_s('F')
 => "5.0" 
1.9.3p194 :003 > BigDecimal.new('5').to_s
 => "5.0" 
1.9.3p194 :004 > BigDecimal.new('5').to_f
 => 0.0 
1.9.3p194 :005 > number_to_currency(5)
 => "€ 0,00"

With some debugging, I narrowed it down to the number_with_precision method, more precisely to the line:

rounded_number = BigDecimal.new(number.to_s).round(precision).to_f

If I output the different parts of this line, I get the following results:

number = 5.0
number.to_s = "5.0"
precision = 2
BigDecimal.new(number.to_s) = 5.0
BigDecimal.new(number.to_s).round(precision) = 5.0
BigDecimal.new(number.to_s).round(precision).to_f = 0.0

Any clue?

Just a shot in the dark: This might be a locale-dependant formatting issue of the Ruby/Rails console.

Try this:

BigDecimal.new('5').to_s('F')  # Should be "5.0"
BigDecimal.new('5').to_i       # Should be 5

If this ouputs the expected result, then it is just a formatting issue of the console. The to_f method actually returns the correct result, but the console calls another to_s on the result in order to print it. In that case you should be able to reproduce the problem with 5.to_f , too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM