简体   繁体   中英

Ruby Rounding Convention

I'm trying to define a function that respects the following rounding conditions (round to the closest integer or tenth):

在此处输入图片说明

The main issue I found out, was around rounding negative numbers.

Here is my implementation (sorry for the conditional check but its just for this example):

  def convention_round(number, to_int = false)
    if to_int
      number.round
    else
      number.round(1)
    end
  end

  convention_round(1.2234) # 1.2
  convention_round(1.2234, true) # 1

  convention_round(1.896) # 1.9
  convention_round(1.896, true) # 2

  convention_round(1.5) # 1.5
  convention_round(1.5, true) # 2

  convention_round(1.55) # 1.6
  convention_round(1.55, true) # 2

  convention_round(-1.2234) # -1.2
  convention_round(-1.2234, true) # -1

  convention_round(-1.896) # -1.9
  convention_round(-1.2234, true) # -2

  convention_round(-1.5) # -1.5
  convention_round(-1.5, true) # -2 (Here I want rounded to -1)

  convention_round(-1.55) # -1.6 (Here I want rounded to -1.5)
  convention_round(-1.55, true) # -2

I'm not 100% sure what is the best approach for rounding the negative numbers.

Thank you!

From the docs, you can use Integer#round (and Float#round ) for this, as follows:

def convention_round(number, precision = 0)
  number.round(
    precision,
    half: (number.positive? ? :up : :down)
  )
end

convention_round(1.4)      #=> 1
convention_round(1.5)      #=> 2
convention_round(1.55)     #=> 2
convention_round(1.54, 1)  #=> 1.5
convention_round(1.55, 1)  #=> 1.6

convention_round(-1.4)      #=> -1
convention_round(-1.5)      #=> -1 # !!!
convention_round(-1.55)     #=> -2
convention_round(-1.54, 1)  #=> -1.55
convention_round(-1.55, 1)  #=> -1.5 # !!!

This isn't quite the method signature you asked for, but it's a more generic form - since you can supply an arbitrary precision.

However, I would like to point out the irony that (despite the method name) this is not a conventional way of rounding numbers.

There are a few different conventions, all(?) of which are supported by the ruby core library (see above link to docs), but this is not one of them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM