简体   繁体   中英

How can I convert a float in a str without losing significant figures?

I want to convert the number 0.054000 in a str , but when I write srt(0.054000) I get '0.054' . I need to get '0.054000' . How can I do it?

I have a data file with numbers as my example (0.054000). I need to count the digits of each number. I don't know how to read that number in a way that I count seven digits, for instance.

I think that Dan Patterson's method is the only way to do it reliably - python makes no differentiation between .0054 and .054000: eg

>>> .0054 is .0054000
True

Thus you will probably have to simply specify the number of digits you have in sig figs, either using his method or (str(.0054000) + "0"*number_of_sig_figs) .

A format specifier starts with a colon and then may contain any of the terms shown in brackets in the following (each of the terms is optional)

: [[fill]align] [sign] [#] [0] [width] [,] [.precision] [type]

A brief description of the [.precision] is provided below.

.precision : Maximum number of characters for strings (integer); number of digits of precision for floats. For f, F, e, and E type specifiers this is the number of digits to the right of the decimal point.

We can use this to specify the precision of our float value:

a=0.540000
print("{:06f}".format(a))

This gives the desired output:

0.540000

Hope this was helpful!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM