Asher Walther
Asher Walther

Reputation: 1327

reading and storing numbers in perl without a loss of percision (Perl)

I have a few numbers in a file in a variety of formats: 8.3, 0.001, 9e-18. I'm looking for an easy way to read them in and store them without any loss of precision. This would be easy in AWK, but how's it done in Perl? I'm only open to using Perl. Thanks!

Also, I was wondering if there's an easy way to print them in an appropriate format. For example, 8.3 should be printed as "8.3" not "8.3e0"

Upvotes: 2

Views: 468

Answers (2)

Barton Chittenden
Barton Chittenden

Reputation: 4416

From http://perldoc.perl.org/perlnumber.html:

Perl can internally represent numbers in 3 different ways: as native integers, as native floating point numbers, and as decimal strings. Decimal strings may have an exponential notation part, as in "12.34e-56" . Native here means "a format supported by the C compiler which was used to build perl".

This means that printing the number out depends on how the number is stored internal to perl, which means, in turn, that you have to know how the number is represented on input.

By and large, Perl will just do the right thing, but you should know how what compiler was used, how it represents numbers internally, and how to print those numbers. For example:

 $ perldoc -f int

 int EXPR

      int  Returns the integer portion of EXPR.  If EXPR is omitted, uses $_.  You should
      not use this function for rounding: one because it truncates towards 0, and two
      because machine representations of floating-point numbers can sometimes produce
      counterintuitive results.  For example, "int(-6.725/0.025)" produces -268 rather than
      the correct -269; that's because it's really more like -268.99999999999994315658
      instead.  Usually, the "sprintf", "printf", or the "POSIX::floor" and
      "POSIX::ceil" functions will serve you better than will int().

I think that if you want to read a number in explicitly as a string, your best bet would be to use unpack() with the 'A*' format.

Upvotes: 1

Mark Reed
Mark Reed

Reputation: 95252

If they're text strings, then reading them into Perl as strings and writing them back out as strings shouldn't result in any loss of precision. If you have to do arithmetic on them, then I suggest installing the CPAN module Math::BigFloat to ensure that you don't lose any precision to rounding.

As to your second question, Perl doesn't do any reformatting unless you ask it to:

$ perl -le 'print 8.3'
8.3

Am I missing something?

Upvotes: 4

Related Questions