Tony Xu
Tony Xu

Reputation: 3081

how to round number according to given example number

my variable is 12.2345678

If given 23.45, then I want to print 12.23

If given 23.456, then I want to print 12.234

Like printf "%.1f", $var where .1 would change according to .2f if given number of 23.45 or .3f if given number of 23.456

Upvotes: 1

Views: 110

Answers (2)

Borodin
Borodin

Reputation: 126722

sprintf will use an argument for the precision of a field if you specify it with an asterisk, for example sprintf '%.*2f', 2, 3.14159 results in "3.14".

My solution would be something like this. Note that 12.2345678 rounded to three decimal places is 12.235, not 12.234 as you requested. If you need truncation instead then you need a different solution.

use strict;
use warnings;

my $var = 12.2345678;

for my $template ('23.45', '23.456') {
  $template =~ /(\d*)\z/;
  my $rounded = sprintf '%.*f', length $1, $var;
  print $rounded, "\n";
}

output

12.23
12.235

Upvotes: 1

paddy
paddy

Reputation: 63461

Count up the number of digits that follow the decimal, then use that value to construct the printf format. ie

$result = sprintf( "%.${count}f", $num );

Upvotes: 4

Related Questions