Home > Software engineering >  Why can't I interpolate the precision for floats in Perl's sprintf?
Why can't I interpolate the precision for floats in Perl's sprintf?

Time:10-31

what should I do? I want the amount of digits to be configurable

I've tried the following:

my $digits = 2;
my $test = 5.42223;
$test = sprintf ("%.$digits\f", $test);
print "$test \n";

but it won't work, it would print "%.2" I should get 5.42

EDIT: I've used the following: my $digits = 2; $digits="$digits"."f"; and it works

CodePudding user response:

Doing it by interpolating the value within the format string just requires putting the variable name in braces to delineate where the variable name stops and the format specifier 'f' starts:

sprintf ("%.${digits}f", $test)

Or you can use '*' as the format width which causes sprintf to get the value from the next argument:

sprintf ("%.*f", $digits, $test);

CodePudding user response:

You almost have it right, but there are two things to consider:

  1. Perl takes the longest name (identifier) possible when it guesses what the variable is. Your code looks like you know that, and Dave gives you the answer for that. use strict can help with this.

  2. A double quoted context also interpolates other things, such a the sequence \n to a newline. The sequence \f is a form-feed. As such, sprintf never sees a format specifier because the f has disappeared from the string.

  •  Tags:  
  • perl
  • Related