Ruby Big Decimal Rounding with fixed number

10,742

Unlike, for example, Java's BigDecimal, Ruby's BigDecimal does not have a per-instance precision. The difference between 3.2 and 3.20 in a Ruby BigDecimal is just formatting.

Share:
10,742
Abid
Author by

Abid

Freelance Ruby/Rails/Javascript/React/Angular Developer

Updated on June 28, 2022

Comments

  • Abid
    Abid almost 2 years

    I want to round a BigDecimal in ruby. I know I can use the round function but

    the round function gives

    (3.2).round(2) =>  3.2
    

    I want

    (3.2).round(2) =>  3.20
    (3.20).round(2) =>  3.20
    (3).round(2) =>  3.00
    (3.578).round(2) =>  3.58
    

    I always want to have 2 decimal places, 3.20 not 3.2

    any idea how to get this done ?