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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With