I have some data here in a text file which I have use regular expression to parse the data
from the file and store the number and index in two variables. I would like to rounded the numbers to same decimal place and write it into a new file (with it’s index A,B,C)
This set of data is all in 3 decimal place
A 11,000.233
B 4.000
C 14,798.241
Another set of data is in 2 decimal place
A 11,000.23
B 4.00
C 14,798.24
They are all in string format initially when I read them using readlines()
But when I convert the string in the first set of data to float and then round it from 3 decimal place to 2 decimal place by using str(round(float(number),2))
I have encountered two problems
-
It will give me an ValueError for A (11,000.233) and C (14,798.241)
I understand it is caused by the , in 11,000.23. But I don’t know how to deal with it.Could anyone give me some suggestion on how to deal with it?
-
For B, when I try to convert the numbers with the same method, it give me 4.0 instead of 4.00. Is there anyway that can output 4.00 instead of 4.0?
split the string at
","and use"".join():you can use string formatting to get
4.00: