-1

I used float to read a number in a text file. for example : number=float(25.0000) ,then I tried to write this number in another file, so I used str format. But what I saw in my text file was like 25.0 .I like to know what should I do to have exactly the number that I had before.(25.0000) I also like to know if even I don't know how many decimal the number has it is possible or not?

with open(file , 'w') as f:
    num =float(25.0000)
    f.write(str(num))
Mahdi.M
  • 55
  • 7
  • You do have the same number, what you do not have is the same string representation of that number. Suggest: https://docs.python.org/2/library/string.html – Stephen Rauch Jan 17 '17 at 03:09

3 Answers3

2

Use the format() function:

with open(file, 'w') as f:
    num = float(25.0000)
    f.write(str(format(num, '.4f')))
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40
2

This will work..

num=float(25.0000)
f=open('a.txt','w')
f.write("%0.4f"%num)

Here, % is the text formatting operator and 0.5 is replaced by the general syntax <fieldWidth>.<precission> and f stands for float data type.

1

You can get your desired result with:

with open(file, 'w') as f:
    num = float(25.0000)
    f.write('%.4f' % num))

(DOCS)

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
  • That is a problem without an easy answer. One possible answer is here: http://stackoverflow.com/a/23749691/7311767 If you read the number out of a file, you can check then. You can also work with fixed point numbers. Or maybe study the sceince a bit: https://en.wikipedia.org/wiki/Significant_figures – Stephen Rauch Jan 17 '17 at 20:50