Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Rounding numbers

Status
Not open for further replies.

r2d22y

Technical User
Nov 30, 2004
46
0
0
SE
Hello

I have some values that are on format:
1.324567788665
1.567678678688

but I wat them to be like:

1.3
1.6

how do I do that in PERL?

Regards/D_S
 
I've written a little function that you can use in your own code.
Code:
#!/usr/bin/perl -w
use strict;

while(<DATA>) {
  chomp;
  print myround($_), "\n";
}

sub myround {
  return int($_*10+0.5)/10;
}

__DATA__
1.324567788665
1.567678678688

Trojan.
 
Here's something you'll want to watch out for with the printf/sprintf functions:
perlfaq4 said:
Rounding in financial applications can have serious implications, and the rounding method used should be specified precisely. In these cases, it probably pays not to trust whichever system rounding is being used by Perl, but to instead implement the rounding function you need yourself.

To see why, notice how you'll still have an issue on half-way-point alternation:

for ($i = 0; $i < 1.01; $i += 0.05) { printf "%.1f ",$i}

0.0 0.1 0.1 0.2 0.2 0.2 0.3 0.3 0.4 0.4 0.5 0.5 0.6 0.7 0.7
0.8 0.8 0.9 0.9 1.0 1.0

Don't blame Perl. It's the same as in C. IEEE says we have to do this. Perl numbers whose absolute values are integers under 2**31 (on 32 bit machines) will work pretty much like mathematical integers. Other numbers are not guaranteed.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top