pankanaj pankanaj - 3 months ago 14
Perl Question

How to use sprintf in Perl to get a float variable upto 2 decimal places without being rounded off

Consider:

my $var = 37.43745;
my $res = sprintf("%.2f",$var);
print $res;


The above code will give the output as 37.44. But I want output to be 37.43 only. How can I get it using sprintf in a Perl script?

Answer
my $var = 37.43745;

my $res = sprintf("%.2f", int($var * 100) / 100);

print $res;