bennett_an
bennett_an

Reputation: 1708

Round date to first year of the decade in Ruby

In Rails, I have a date saved in an instance variable. I need to grab the beginning of the decade before it. If @date.year= 1968 then I need to return 1960. How would I do that?

Upvotes: 1

Views: 755

Answers (3)

sunnyrjuneja
sunnyrjuneja

Reputation: 6123

You can do this several ways. As suggested, you can always use integer division which divides the number and truncates the remainder. So 1968/10 returns 196 and if you multiply it by 10, it will give you 1960. Or simply,

@date.year = @date.year/10 * 10
@date.year 
=> 1960

I prefer the method of using modular arithmetic. If you do @date.year % 10 it will return the remainder if you divide by 10 which you can then subtract from the year like so:

@date.year = @date.year - (@date.year % 10)
@date.year 
=> 1960

The reason I prefer the latter is because integer division truncating the remainder may not be some thing that is obvious to everyone looking at your code. However, modular arithmetic works generally the same in all programming languages.

Keep in mind if you're trying to change the date, you need to use the appropriate method.

@date.change(:year => 1960)

Upvotes: 7

Ken Li
Ken Li

Reputation: 2618

Do an integer division by 10, and then multiply by 10.

1.9.3-p286 :001 > 1855/10
 => 185 
1.9.3-p286 :002 > 185 * 10
 => 1850 

The reason why this works (in Ruby, and in C/C++, Python, and possibly many other languages), is that integer division will always truncate the remainder. This will not be the case if you are dividing by a floating point however.

Upvotes: 2

davidrac
davidrac

Reputation: 10738

just divide and multiply integers: try @date.year/10*10

Upvotes: 3

Related Questions