Python customization Decimal range of places without rounding?

How can I take the float variable and control how far the float goes without round ()? For instance.

w = float(1.678)

I want to take x and make the following variables from it.

x = 1.67
y = 1.6
z = 1

If I use the appropriate round methods:

x = round(w, 2) # With round I get 1.68 
y = round(y, 1) # With round I get 1.7
z = round(z, 0) # With round I get 2.0

He's going to round up and change the numbers to such an extent that I have nothing to use. I understand that this is a question of the round, and it works correctly. How do I get the information I need in the variables x, y, z, and still use them in other equations in float format?

+14
source share
3 answers

You can do:

def truncate(f, n):
    return math.floor(f * 10 ** n) / 10 ** n

Testing:

>>> f=1.923328437452
>>> [truncate(f, n) for n in range(7)]
[1.0, 1.9, 1.92, 1.923, 1.9233, 1.92332, 1.923328]
+16
source

Super simple solution is to use strings

x = float (str (w)[:-1])
y = float (str (w)[:-2])
z = float (str (w)[:-3])

, , / 10 .

+3

If you just need to control the accuracy of the format

pi = 3.14159265
format(pi, '.3f') #print 3.142 # 3 precision after the decimal point
format(pi, '.1f') #print 3.1
format(pi, '.10f') #print 3.1415926500, more precision than the original

If you need to control precision in floating point arithmetic

import decimal
decimal.getcontext().prec=4 #4 precision in total
pi = decimal.Decimal(3.14159265)
pi**2 #print Decimal('9.870') whereas '3.142 squared' would be off

- edit -

Without "rounding", thus trimming the number

import decimal
from decimal import ROUND_DOWN
decimal.getcontext().prec=4
pi*1 #print Decimal('3.142')

decimal.getcontext().rounding = ROUND_DOWN
pi*1 #print Decimal('3.141')
0
source

All Articles