Swati Sucharita
Swati Sucharita

Reputation: 64

Rails 2 - Absolute of money

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.

Upvotes: 2

Views: 1259

Answers (2)

yakattack
yakattack

Reputation: 159

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

Upvotes: 0

Ian McLaird
Ian McLaird

Reputation: 5585

Try taking the absolute value before converting to money.

2.abs.to_money

Upvotes: 7

Related Questions