Search code examples
rubybigdecimal

Can I wrap equations in BigDecimal?


@amount ||= BigDecimal( @price * ( @tax_percentage / 100) ).round(2)

Is it ok to wrap an equation in BigDecimal like this? Or do I need to cast each individual component to BigDecimal?


Solution

  • Similar to working with float, you need to cast one of the elements to BigDecimal to have the whole value return BigDecimal

    @amount ||= (@price * ( BigDecimal(@tax_percentage) / 100) ).round(2)
    

    In the sample above I've cast @tax_percentage to BigDecimal and not @price, since otherwise, if originally @tax_percentage was integer, dividing it by 100 will result in loss of data - the result would be integer...

    5 / 100
    # => 0
    
    BigDecimal(5) / 100
    # => 0.05