开发者

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).

  1. Import file into spreadsheet application
  2. Change formatting on relevant columns
  3. 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:

  1. Write an another tool only for parsing your set of files.
  2. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜