Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I impose the total number of digits in python (new formatting)

I would like to keep the total number of digits (before and after the decimal point) of a float constant in python.

For example, if I want to impose a fixed width of 7: 1234.567890123 would become 1234.567 but 12345.678901234 would become 12345.67

Fixing the number of decimals does not work in this case since it depends on how many digits I have before the decimal point. I also tried the [width] option but it impose a minimum width and I need a maximum.

Thanks for your input!

like image 997
Fanny Avatar asked Oct 22 '25 12:10

Fanny


1 Answers

Just by using your example,

a = 1234.567890123 
b = 12345.678901234
str(a)[:8] # gives '1234.567'
str(b)[:8] # gives '12345.67'
like image 200
Hun Avatar answered Oct 25 '25 00:10

Hun