# Does Perl have a built in truncate command?

#### Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

•  Subject
• Author
• Posted on
Hi All,

Does Perl have a built in truncate command?

I am finding various ways with string command to chop up
a real,

http://www.perlmonks.org/?node_id=328366

but I was wondering if there is a build in command
somewhere for it.

For instance:

3.141592654

Truncate at 4th digit

3.1415

Round at the 4th would be

3.1416

Many thanks,
-T

## Re: Does Perl have a built in truncate command?

There's no builtin way to do that but a sensible implementation is

------
sub trunc
{
my (\$n, \$fracs) = @_;
return int(\$n * 10 ** \$fracs) / 10 ** \$fracs;
}

print(trunc(\$ARGV[0], \$ARGV[1]), "\n");
------

ie multpliy the number with a suitable factor for ensuring that all
wanted digits are now before the point, use int(...) to strip of the
fractional part, divide by the same factor to move the originally
fractional digits back.

NB: Since this is using floating point operations, the actual result may
be different from the intended result.

## Re: Does Perl have a built in truncate command?

sprintf does it for you including the rounding.

sub round      # Round to 4 decimal places
{
my \$value = shift;
\$value = sprintf "%.4f", \$value;
}

John Black

## Re: Does Perl have a built in truncate command?

[...]

Not really. sprintf formats the value as a string with a certain number
of fractional digits. This string is then possibly converted back to a
number if future operations require that, cf

------
use Devel::Peek;

my \$x = 3.141592654;
my \$y = \$x;

sub round
{
my (\$n, \$fracs) = @_;
return int(\$n * 10 ** \$fracs + 0.5) / 10 ** \$fracs;
}

\$x = round(\$x, 4);
\$y = sprintf('%.4f', \$y);

Dump(\$x);
print "====\n";
Dump(\$y);
-------

NB: I don't think it's possible to distinguish both via Perl.

## Re: Does Perl have a built in truncate command?

On Wednesday, December 30, 2015 at 12:32:07 PM UTC-8, Rainer Weikusat wrote:

sprintf would round rather than truncate and the result would
be stored as a PV but there's no problem with that.

Also suggested in perlmonks were solutions using substitute, eg

\$n =~ s/\.(\d\d+/\$1/;