float to string with different precision

Z

zunbeltz

Hi,

I have to print float numbers to a file. Each float should be 5
characters in width (4 numbers and the decimal point).
My problem is that I do not now how to specify float to have different
numbers of decimals. For example

5.32 -> 5.320
10.356634 -> 10.357
289.234 -> 289.2

In the string formating operations only fixed number of decimal digits
is allow.

Thanks in advance for the help,

Zunbeltz
 
P

Peter Otten

I have to print float numbers to a file. Each float should be 5
characters in width (4 numbers and the decimal point).
My problem is that I do not now how to specify float to have different
numbers of decimals. For example

5.32 -> 5.320
10.356634 -> 10.357
289.234 -> 289.2

In the string formating operations only fixed number of decimal digits
is allow.
["%#.4g" % f for f in [5.32, 10.356634, 289.234, 123456789.]]
['5.320', '10.36', '289.2', '1.235e+08']

Found by playing around with format strings, so no guarantees.

Peter
 
Z

Zentrader

I have to print float numbers to a file. Each float should be 5
characters in width (4 numbers and the decimal point).
My problem is that I do not now how to specify float to have different
numbers of decimals. For example
5.32 -> 5.320
10.356634 -> 10.357
289.234 -> 289.2
In the string formating operations only fixed number of decimal digits
is allow.
["%#.4g" % f for f in [5.32, 10.356634, 289.234, 123456789.]]

['5.320', '10.36', '289.2', '1.235e+08']

Found by playing around with format strings, so no guarantees.

Peter

If the above does not work
[/code]test_list = [ 5.32, 10.35634, 289.234 ]
for num in test_list :
str_num = "%11.5f" % (num) ## expand to at least 5
print str_num, "-->", str_num.strip()[:5][/code]
 
R

Roger Miller

If the above does not work
[/code]test_list = [ 5.32, 10.35634, 289.234 ]
for num in test_list :
str_num = "%11.5f" % (num) ## expand to at least 5
print str_num, "-->", str_num.strip()[:5][/code]

This has the disadvantage that it doesn't round the last digit. For
example 10.356634 yields 10.356 instead of 10.357.

You can use '*' in format strings to take a numeric field value from a
variable. For example

ndecimals = 2
print "%5.*f" % (ndecimals, x)

formats x with 2 digits following the decimal point. Or you can
simply
cobble up a format string at run time:

format = "%%5.%df" % ndecimals
print format % x
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,011
Latest member
AjaUqq1950

Latest Threads

Top