Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncate to three decimals in Python

Tags:

python

How do I get 1324343032.324?

As you can see below, the following do not work:

>>1324343032.324325235 * 1000 / 1000 1324343032.3243253 >>int(1324343032.324325235 * 1000) / 1000.0 1324343032.3239999 >>round(int(1324343032.324325235 * 1000) / 1000.0,3) 1324343032.3239999 >>str(1324343032.3239999) '1324343032.32' 
like image 261
SuperString Avatar asked Dec 21 '11 20:12

SuperString


People also ask

How do you truncate to 3 decimal places?

To truncate a number to 3 significant figures, miss off all the digits after the first 3 significant figures (the first non-zero digit and the next two digits). Fill in any spaces with zeros to make the number approximately the same size as the original value.

How do you truncate decimals in a list Python?

Use the int Function to Truncate a Float in Python The built-in int() function takes a float and converts it to an integer, thereby truncating a float value by removing its decimal places.

How do you truncate two decimals in Python?

Python's round() function requires two arguments. First is the number to be rounded. Second argument decides the number of decimal places to which it is rounded. To round the number to 2 decimals, give second argument as 2.


2 Answers

You can use an additional float() around it if you want to preserve it as a float.

%.3f'%(1324343032.324325235) 
like image 87
Abhranil Das Avatar answered Sep 27 '22 21:09

Abhranil Das


You can use the following function to truncate a number to a set number of decimals:

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

Usage:

>>> truncate(1324343032.324325235, 3) 1324343032.324 
like image 26
Erwin Mayer Avatar answered Sep 27 '22 19:09

Erwin Mayer