Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set a variable to divide and round up to 0 decimal places?

Tags:

ruby

In Ruby, how can I do:

number_total = records / per_page

where per_page = 100, and records = 1050, and then round up so there are no decimals? So, instead of 10.5 it equals 11?

like image 991
AnApprentice Avatar asked May 10 '11 01:05

AnApprentice


People also ask

How do you round up a variable in Python?

Python's Built-in round() Function Python has a built-in round() function that takes two numeric arguments, n and ndigits , and returns the number n rounded to ndigits . The ndigits argument defaults to zero, so leaving it out results in a number rounded to an integer.

How do you round decimal places in Python?

Round() Round() is a built-in function available with python. It will return you a float number that will be rounded to the decimal places which are given as input. If the decimal places to be rounded are not specified, it is considered as 0, and it will round to the nearest integer.

How do you round to 2 decimal places in Python?

Python's round() function requires two arguments. First is the number to be rounded. Second argument decides the number of decimal places to which it is rounded. To round the number to 2 decimals, give second argument as 2.

Does INT () truncate or round?

INT is similar to the TRUNC function because they both can return the integer part of a number. However, TRUNC simply truncates a number, while INT actually rounds a number down to an integer. With positive numbers, and when TRUNC is using the default of 0 for num_digits, both functions return the same results.


2 Answers

Edited following a comment

number_total = (records / per_page.to_f).ceil
like image 100
sawa Avatar answered Sep 21 '22 17:09

sawa


@lulala Another root of all evil: cherry-picking results.

Run your benchmark multiple times. I get the following:

       user     system      total        real
   0.120000   0.000000   0.120000 (  0.119281)
   0.120000   0.000000   0.120000 (  0.123431)

Which is a tie.

       user     system      total        real
   0.110000   0.000000   0.110000 (  0.118602)
   0.130000   0.000000   0.130000 (  0.127195)

Which suggests that float_op is faster.

       user     system      total        real
   0.150000   0.000000   0.150000 (  0.151104)
   0.120000   0.000000   0.120000 (  0.123836)

Which suggests that integer_op us faster.

like image 44
Khalil Fazal Avatar answered Sep 19 '22 17:09

Khalil Fazal