Marios Ath
Marios Ath

Reputation: 638

Round up instead of down when below zero

It seems Ruby chooses to round negative numbers down instead of closer to zero.

-1.5.round
#=>-2

Whereas positive numbers work the other way:

2.5.round
#=>3

How do I round up negative numbers(closer to zero) instead of rounding them down? I'm using ruby version 2.2.2.

Upvotes: 1

Views: 291

Answers (2)

Edinho Zanutto
Edinho Zanutto

Reputation: 1

Maybe you have to make some adjusts to round as you want:

    def roundy(x)
  x.to_i
  if x<0
    puts (x. + 0.1).round
  else puts x.round
  end
end

Upvotes: 0

Philip Hallstrom
Philip Hallstrom

Reputation: 19879

This should work.

> (-1.5+0.5).floor
=> -1
> (-1.4+0.5).floor
=> -1
> (-1.6+0.5).floor
=> -2

Upvotes: 3

Related Questions