Truncate a decimal value in Python

2019-02-08 07:49发布

问题:

I am trying to truncate a decimal value in Python. I don't want to round it, but instead just display the decimal values upto the specified accuracy. I tried the following:

d = 0.989434
'{:.{prec}f}'.format(d, prec=2)

This rounds it to 0.99. But I actually want the output to be 0.98. Obviously, round() is not an option. Is there any way to do this? Or should I go back to the code and change everything to decimal?

Thanks.

回答1:

I am not aware of all your requirements, but this will be fairly robust.

>> before_dec, after_dec = str(d).split('.')
>> float('.'.join((before_dec, after_dec[0:2])))
0.98

2018-01-03 edit

This answer isn't robust or mathematically correct. See Nilani Algiriyage's answer below for the correct way to do this using Decimal.quantize method.



回答2:

You can use following code

import decimal
d = 0.989434

print decimal.Decimal(d).quantize(decimal.Decimal('.01'), rounding=decimal.ROUND_DOWN)


回答3:

d = 0.989434
print floor(d * 100) / 100

Math.floor(x) Return the floor of x as a float, the largest integer value less than or equal to x.

Moving the 2 decimals on the left of the decimal '.', flooring, then moving back the numbers on the right of the '.'

100 can be modifying by

n = 2
m = pow (10, n)
d = 0.989434
print floor(d * m) / m

n is your wanted precision.

EDIT: In case d is negative, you have to use the ceil method

if d < 0:
    print ceil(d * m) / m
else:
    print floor(d * m) / m


回答4:

Format it to something much longer and then cut off the extra digits:

def truncate(f, digits):
    return ("{:.30f}".format(f))[:-30+digits]


回答5:

This is the best way I believe.

  1. Move the significant digits to the left
  2. Truncate the decimal part
  3. Move the number of digits moved to left, to right

    d = 0.989434
    print "{0:0.2f}".format(int(d * 100)/100.0)
    

    Output

    0.98
    


回答6:

import math

d = 0.989434
prec = 2
output = math.floor(d * (10 ** prec)) / (10 ** prec)

If you still want a decimal variable instead of string



回答7:

Fairly similar to some other answers, but without any imports

def truncate(x, d):
    return int(x*(10.0**d))/(10.0**d)

>>>truncate(0.987654, 2)
0.98


回答8:

with str:

d = str(0.989434)
print float(d[:d.find('.')+3])


回答9:

If you only need to display you can convert it to string and slice it :

d = 0.989434
print str(d)[0:4] #or print(str(d)[0:4])


回答10:

The code below will print 0.98 in this case, though you'll have to be careful that your d value doesn't become larger than or equal to 10 as then it'll only print, for e.g., 10.1 rather than 10.12.

d = 0.989434
print '{:.{prec}s}'.format(str(d), prec=4)


回答11:

Also with math:

d = 0.989434
x = int(d * 100.0) / 100.0
print "{0:0.2f}".format(x)


回答12:

In this link here I posted the solution below:

def truncate_number(f_number, n_decimals):
      strFormNum = "{0:." + str(n_decimals+5) + "f}"
      trunc_num = float(strFormNum.format(f_number)[:-5])
      return(trunc_num)

# Testing the 'trunc_num()' function
test_num = 1150/252
[(idx, truncate_number(test_num, idx)) for idx in range(0, 20)]

At leat it doesn't require to load any module nor demands new calculations. So far, it solved my problem with the truncation requirements in public bond prices calculations.