René Nyffenegger
René Nyffenegger

Reputation: 40533

Can I specify a maximum precision width for numbers with sprintf in Perl?

Is it possible to use Perl's sprintf function to specify a maximum precision width for floating point number? After reading the documentation, I believe it's not, but may be I have overlooked something.

So, if I have have 4.12, I'd like to have the number formated as 4.12.

my $abc = 4.12;
my $out = sprintf("%?...", $abc); # $out eq '4.12';

Yet, if the number has more than 6 digits of precision, I want only 6 digits:

my $def = 1.23456789;
my $out = sprintf("%?...", $def); # $out eq '1.234568';

Is this possible with sprintf?

Edit

Currentyl, I am using

sub output_number {
  my $number = shift;

  my $ret = sprintf("%.6f", $number);

  $ret =~ s/0*$//g;
  $ret =~ s/\.$//g;

  return $ret;
}

for my purposes, which does what I need. But I hoped there is a more elegant way. Preferably a one liner, not necessarily restricted to the use of sprintf.

Note also, that the suggested printf ("%.7g", $number) doesn't behave the way I want (for example for $n = 0.00000000001;.

Upvotes: 3

Views: 632

Answers (1)

mob
mob

Reputation: 118635

I believe you can use %.<n>g:

perl -e 'printf "%.7g", 4.12'          =>   4.12
perl -e 'printf "%.7g", 4.12345678'    =>   4.123457

But if exponential notation really ruins your day, and your installed perl is modern enough, there's always

sprintf("%.6f",$number) =~ s/\.?0+$//r

Upvotes: 4

Related Questions