money icon indicating copy to clipboard operation
money copied to clipboard

Comparison between two currencies (greater/less than)

Open installero opened this issue 4 years ago • 2 comments

Can I compare two objects in different currencies? I've searched throug the issues and found only this thread. Where only equality is discussed.

I wonder if understanding which on is greater/less is useful (seems so).

rub = Money.new(75_00, 'RUB')
usd = Money.new(1_00, 'USD')

Money.add_rate("USD", "RUB", 74.90)

usd < rub

Traceback (most recent call last):
        5: from /home/install/.rvm/rubies/ruby-2.7.2/bin/irb:23:in `<main>'
        4: from /home/install/.rvm/rubies/ruby-2.7.2/bin/irb:23:in `load'
        3: from /home/install/.rvm/rubies/ruby-2.7.2/lib/ruby/gems/2.7.0/gems/irb-1.2.6/exe/irb:11:in `<top (required)>'
        2: from (irb):13
        1: from (irb):13:in `<'
ArgumentError (comparison of Money with Money failed)

installero avatar Mar 24 '21 11:03 installero

The current behaviour is when you compare USD with RUB. The code converts the RUB to USD and than compare USD to USD. The reason you are seeing the above exception is because it is not possible to convert RUB to USD. You need to add the rate for RUB to USD eg. `Money.add_rate("RUB", "USD", 0.013) so that RUB is converted to USD and the comparison works.

The modified code as follows below: rub = Money.new(75_00, 'RUB') usd = Money.new(1_00, 'USD') Money.add_rate("RUB", "USD", 0.013) usd < rub => false

I hope this helps and please let me know if you have any other questions. Thank you.

deepakhb2 avatar Mar 24 '21 22:03 deepakhb2

one quick follow-up, the reason is does not intuit the reverse is that currencies do not always covert between each other consistently. Most of the time it does, but when it does not, it causes severe issues,

semmons99 avatar Mar 25 '21 01:03 semmons99