By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,270 Members | 1,703 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,270 IT Pros & Developers. It's quick & easy.

float to string with different precision

P: n/a
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

Aug 10 '07 #1
Share this Question
Share on Google+
3 Replies


P: n/a
zu******@gmail.com wrote:
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
Aug 10 '07 #2

P: n/a
On Aug 10, 1:12 am, Peter Otten <__pete...@web.dewrote:
zunbe...@gmail.com wrote:
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]

Aug 10 '07 #3

P: n/a
On Aug 10, 8:37 am, Zentrader <zentrad...@gmail.comwrote:
>
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

Aug 10 '07 #4

This discussion thread is closed

Replies have been disabled for this discussion.