Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python round leaving a trailing 0 [duplicate]

Tags:

python

I am trying to round a floating point number in python to zero decimal places.

However, the round method is leaving a trailing 0 every time.

value = 10.01
rounded_value = round(value)
print rounded_value

results in 10.0 but I want 10

How can this be achieved? Converting to an int?

like image 589
Marty Wallace Avatar asked May 26 '13 20:05

Marty Wallace


People also ask

How do you keep trailing 0 in Python?

Python string method ljust() returns the string left justified in a string of length width. Padding is done using the specified fillchar (default is a space). The len() returns the length of the string. We add trailing zeros to the string by manipulating the length of the given string and the ljust function.

How do you keep a zero after a decimal in Python?

Use the format() function to add zeros to a float after the decimal, e.g. result = format(my_float, '. 3f') . The function will format the number with exactly N digits following the decimal point.

Is it OK to have a trailing zero after a whole number?

In addition, a whole number should never be followed by a decimal point and a zero. These "trailing zeros" (e.g., 3.0) are a frequent cause of 10-fold overdoses and should never be used. For example, when prescriptions have been written for "Coumadin 1.0 mg," patients have received 10 mg in error.


1 Answers

Pass the rounded value to int() to get rid of decimal digits:

>>> value = 10.01
>>> int(round(value))
10
>>> value = 10.55
>>> int(round(value))
11
like image 96
Ashwini Chaudhary Avatar answered Sep 22 '22 23:09

Ashwini Chaudhary