user3350919
user3350919

Reputation: 253

Printing floating-point numbers with

I have the following "help" subroutine:

sub help {

print <<HELP;

   useage:  the script will apply a constant set of changes on the code files

   Flags:
   -dest:   The output directory, 
   -source: The path to the directory where the source code is. 
   -ver:    The version of the code (default = $version)

HELP
    exit 0;
}

The variable $version is set to 3.0, but when I call the subroutine, it only prints:

   -ver:                     The version of the code (default = 3)

i.e., it does not print the dot and the zero.

How can I fix this?

Upvotes: 0

Views: 82

Answers (2)

Sinan &#220;n&#252;r
Sinan &#220;n&#252;r

Reputation: 118118

Use printf:

sub help {
    printf(<<HELP, $version);
usage:  the script will apply a constant set of changes on the code files

Flags:
   -dest:   The output directory,
   -source: The path to the directory where the source code is.
   -ver:    The version of the code (default = %.1f)
HELP
    exit 0;
}

Output:

Usage:  the script will apply a constant set of changes on the code files

Flags:
   -dest:   The output directory,
   -source: The path to the directory where the source code is.
   -ver:    The version of the code (default = 3.0)

Upvotes: 2

Sobrique
Sobrique

Reputation: 53478

Either specify the version as a string:

my $version = "3.0";

Or use printf to specify the precision when printing the numeric value.

printf ( "%.1f", $version );

Or if you really want to get funky about it, make $version a dualvar, that gives different values in string and number context. (This is showing off - it's probably a bad idea for maintainable code).

use strict;
use warnings;
use Scalar::Util qw ( dualvar );

my $version = dualvar ( 3.0,  "three point zero" );

print $version,"\n";
if ( $version >= 3.0 ) { print "3.0 or higher\n" };

If you specify a scalar a value as numeric, perl turns it into a number. 3.0 = 3.00 = 3 and so it'll print with the minimum precision necessary by default. That's why you have this problem.

You may find it useful to look at version too.

Upvotes: 2

Related Questions