Forum: Ruby on Rails 123 * 3 => 123123123! But why?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Fc582698581884352e745d1d4c64699d?d=identicon&s=25 Joshua Muheim (josh)
on 2006-01-20 00:54
Hi all

I extended the Globalize Plugin the following way:

--------
module Globalize
  class Currency
    def conversion_rate
      code = Locale.active.currency_code
      rates = { :USD => 1,
                :CHF => 0.75,
                :EUR => 1.1,
                :GBP => 3.1
              }
      value = rates[code.to_sym]
      raise "No conversion rate found for currency '#{code}'
(#{Locale.active.language.english_name})!" if value.nil?
      value
    end

    def dollar_part
      na? ? nil : cents / 100 / conversion_rate
    end

    def cent_part
      na? ? nil : cents % 100 / conversion_rate
    end
  end
end
--------

Sadly I get ugly results like

$99.00 # correct!
SFr. 132,0.00 # incorrect!
â?¬ 90,0,00 # incorrect!

I don't know why Ruby concatenates the values and does not multiply
them... How can I fix that?

Thanks for help. :-)
Greetings, Josh
3bec49196b296ac7c201412642c7a2b1?d=identicon&s=25 Rodrigo Alvarez (papipo)
on 2006-01-20 01:09
(Received via mailing list)
you are multiplying a string, not a number. Try using .to_f (to float)
method
05d703f649ef1d07e78d7b479fb4c4ac?d=identicon&s=25 James Adam (Guest)
on 2006-01-20 01:12
(Received via mailing list)
If you're finding that 123 * 3 == 123123123, that's almost certainly
because your 123 is actually '123', i.e. a String. You'll need to
ensure that the value you are operating on is a Numeric by converting
it...

- james
Fc582698581884352e745d1d4c64699d?d=identicon&s=25 Joshua Muheim (josh)
on 2006-01-20 01:29
It seems that it's another problem... I have to round the value to a
number without digits after the comma...

1234.2456256 should become 1234

How can i round integer values?
C8a634a01a2c4508360874bff7fb1a7f?d=identicon&s=25 Kevin Olbrich (olbrich)
on 2006-01-20 01:35
Joshua Muheim wrote:
> It seems that it's another problem... I have to round the value to a
> number without digits after the comma...
>
> 1234.2456256 should become 1234
>
> How can i round integer values?

value.round will round to the nearest integer (only works for floats)
value.to_i will truncate the float part off without rounding.

_Kevin
Fc582698581884352e745d1d4c64699d?d=identicon&s=25 Joshua Muheim (josh)
on 2006-01-20 01:38
Thank you, it's working great now. :-)
This topic is locked and can not be replied to.