-3

i have a problem in python3

my variable is

i = 31.807

I would transform in this:

i = 31.80

with two numbers after the decimal point and without round even show 0 in end.

mohsen
  • 11
  • 3

2 Answers2

0

Question: how do I round a float in Python to the desired decimal digit?

You can use numpy.round and supply the value to round and the number of significant digits, i.e.

import numpy as np
i = np.round(31.807, 2)
print(i)

the output is going to be 31.81, which differs from you example.

Question: how do I ceil/floor to the desired decimal digit?

Unfortunately numpy.ceil and numpy.floor do not allow for that, so you need to be a bit more crafy:

import numpy as np
i = np.floor(31.807*100)/100
print(i)

the output is now 31.8.

Question: how do I print a number in a specific format?

Here there is no single write way to go, one possibility is:

print("{:.2f}".format(31.8))

Output: 31.80.

0

I think the solution from this question here: stackoverflow.com/a/37697840/5273907 would solve your problem i.e.:

import math
def truncate(number, digits) -> float:
    stepper = 10.0 ** digits
    return math.trunc(stepper * number) / stepper

When I test it locally with your example I get:

>>> truncate(31.807, 2)
    31.8
Omri Shneor
  • 965
  • 3
  • 18
  • 34