Truncating floating point numbers in file
I am working on a tool which generated a few thousand ASCII files (constraints), the contents of which include floating point numbers. I would like to run these constraints for comparison through an similar tool, which cannot handle floating point values with more than 20 decimal places. Testing manually indicates that simple truncation will suffi开发者_开发技巧ce. So, how can I truncate all floating point values in a file (which are uniquely marked by a period) to no more than 20 decimal places?
Thanks,
Jon
I know for sure in Java and C (and almost certainly in other languages) there are ways to format strings. String.format() and printf() are some good examples. These can be used for case by doing something like:
printf("%.20f", myFloat);
I'll find a website with better instructions in a second.
edit:
this should probably be a good enough link to get an idea:
http://www.cplusplus.com/reference/clibrary/cstdio/printf/
edit:
if you would like to use sed, a quick search makes it seem as though sed has a printf function too. the example I found is here:
http://docstore.mik.ua/orelly/unix/sedawk/ch07_09.htm
It's difficult to tell without more information about your platform and which languages/tools you're comfortable with.
If your file is in a comma or tab delimited or fixed width format I'd try a spreadsheet application (like Excel on Windows or Open Office on other platforms).
- Import file into spreadsheet application
- Change formatting on relevant columns
- Export file into same format
If it's more complex you might try perl or python.
a relevant regex for a tool like sed (or perl) would be:
s/^([0-9]*\.)([0-9]{20})([0-9]*)$/\1\2/g
This regular expression basically matches any string of numbers with a single '.' in it. It divides it into three sections: the part before and including the '.', the next 20 numbers and the remaining numbers. It then outputs the first two sections. You should be able to modify this to match your actual pattern without too much trouble using a regular expression reference.
There are at least two ways that you can solve this problem:
- Write an another tool only for parsing your set of files.
- An implementing a some kind of settings in tool which you are creating now. This settings will control output for all functions that compute values in project or just output in data store structures.
I think second way is best because it's not depend on formating file.
精彩评论