Hello,
Does anyone know how to limit or round a float to only two decimals without rounding up?
for example,
if the number is 3.149, then I want the output to be 3.14. If the number is 3.0, then the output must be 3.00
thank you
rounding - How to round to 2 decimals with Python? - Stack Overflow
How to get float to two decimal places without rounding off.
How to truncate a float?
python - Limiting floats to two decimal points - Stack Overflow
Videos
You can use the round function, which takes as its first argument the number and the second argument is the precision after the decimal point.
In your case, it would be:
answer = str(round(answer, 2))
Using str.format()'s syntax to display answer with two decimal places (without altering the underlying value of answer):
def printC(answer):
print("\nYour Celsius value is {:0.2f}ºC.\n".format(answer))
Where:
:introduces the format spec0enables sign-aware zero-padding for numeric types.2sets the precision to2fdisplays the number as a fixed-point number
Like if I have 8.225 I want 8.22 not 8.23 Do I have to use it as a string first then convert to float? Or is there a simpler way
I have a case where I need to truncate a float to the first decimal place. Very important - truncate, not round.
I wrote this function
def trunc(num : float, precision :int = 1):
return float(str(num)[0:precision+2])
which works most of the time, but if the number is particularly small, str(num) will return the scientific notation. So str(0.000094) returns 9.4e-05 which in turn means that str(0.000094)[0:3] returns 9.4.
For now I can np.trunc(num*10)/10 but I'm wondering if there's a better way.
lambda x, n:int(x*10^n + 0.5)/10^n
has worked for me for many years in many languages.
One-liner function to print percentage:
k - the numerator
n - the denominator
'%.2f' - means you want a precision of 2 decimal places
*100 - turns the number from a decimal to a percentage
percentage = lambda k, n: '%.2f' % (k/n*100)
- equivalent to-
def percentage(k,n):
return '%.2f' % (k/n*100)
percentage(1,3)
output -> '33.33'