Author -  Sai gowtham

How to round a float value to N decimal places in Ruby

In this tutorial, we are going to learn about How to round a float value to N decimal places in Ruby using the round() method.

Consider, we have a float value like this.

num  = 12.1421

Now, we need to format the above float value to 3 decimal places like this 12.142.

Using the round() method

To round a number to N decimal places in Ruby, we can use the round() method by passing N as a argument to it.

N is number of decimal places we need to round the float value.

The round() method takes the number of digits as argument and formats the number into the mentioned decimal places. By default the round() method removes the fractional part.

Let’s see an example:

num  = 12.1421

puts num.round(2)

Output:

12.142

In the example, above we have passed 3 as an argument to the round() method. So that it rounds a float value to 3 decimal places.

Similarly, if you want round a float value to 2 decimal places just pass the 2 as an argument to the round() method.

Here is an example of how to round a float value to 2 decimal places:

num  = 12.1421

puts num.round(2)

Output:

12.14

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY