2

How to get absolute value of money? e.g:

-2.to_money.? = 2.to_money
 2.to_money.? = 2.to_money

I have an attribute total_price, which may be positive or negative. I want to calculate the absolute value of total_price.

2 Answers2

7

Try taking the absolute value before converting to money.

2.abs.to_money

Ian McLaird
  • 5,507
  • 2
  • 22
  • 31
  • Thanks.According to my requirements, I'll have to do `total_price.cents.abs.to_money`. is there any other way? – Swati Sucharita Jul 26 '13 at 09:16
  • 1
    I suppose you could monkey patch or extend the money class to add the needed function, but that seems like a lot of work, and a really bad idea. – Ian McLaird Jul 29 '13 at 00:16
0

There's now an absolute value method built-in to the Money::Arithmetic module:

2.to_money.abs == #<Money fractional:200 currency:USD> # true
-2.to_money.abs == #<Money fractional:200 currency:USD> # true
yakattack
  • 159
  • 2
  • 4