Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
math
round
communitycreator

What is round() in Ruby?

Harris Amjad

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The round() function rounds off a number to a specified number of decimal places.

Figure 1 shows a visual representation of the round() function.

Figure 1: Visual representation of the round() function

Syntax

num.round(ndigits)
#where num is the number which is to be rounded off
#where ndigits is the number of decimal places

Parameter

The parameter ndigits is the number of decimal places to which the above number needs to be rounded off.

This is an optional parameter. Its default value is 0. If ndigits is omitted, then round() returns the nearest integer value of a number.

Return value

The round() function returns the number rounded off to the specified number of decimal places.

If you input a negative value (-n) in the ndigits, then n digits to the left of the decimal point of the number will be rounded off.

Example

#number: postive ndigits: positive
print "(9.8923).round(2):", (9.8923).round(2), "\n"

#number: negative ndigits: positive
print "(-9.8923).round(2): ", (-9.8923).round(2), "\n"

#number: positive ndigits: negative
print "(923.8923).round(-2): ", (923.8923).round(-2), "\n"
print "(989.8923).round(-2): ", (989.8923).round(-2), "\n"

#number: negative ndigits: negative
print "(-923.8923).round(-2): ", (-923.8923).round(-2), "\n"
print "(-989.8923).round(-2): ", (-989.8923).round(-2), "\n"

# no ndigits
print "(9.8923).round():", (9.8923).round(), "\n"
print "(-9.8923).round(): ", (-9.8923).round(), "\n"

RELATED TAGS

ruby
math
round
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring