Rounding Floating-Point Numbers

You want to round a floating-point value to a certain number of decimal places.

Use sprintf or printf Perl functions.

Sample Code: Output:
$a = 0.255; $b = sprintf("%.2f", $a); print "Unrounded:\t$a\nRounded:\t$b\n"; printf "Unrounded:\t$a\nRounded:\t%.2f\n", $a; Unrounded: 0.255
Rounded: 0.26 Unrounded: 0.255
Rounded: 0.26

Also see Chapter 15. Arithmetic Expansion.

Checking if variable is numeric

Scalar::Util

Sample Code: Output:
#!/usr/bin/perl # looks_like_number.pl
use Scalar::Util qw(looks_like_number); foreach $input (@ARGV) { if (looks_like_number($input)) { print "$input \tis a number\n"; } else { print "$input \tis NOT a number\n"; } }
$ looks_like_number.pl 1 A 12.6 a2 4b -12 3e2 1 is a number A is NOT a number 12.6 is a number a2 is NOT a number 4b is NOT a number -12 is a number 3e2 is a number