it's urgent ! round number in perl scripting

my $number = 12.345673412

I need 3 digits after decimal or after dot(.)

i mean , i need only 12.345

I used int(), ceil(), floor() but it gives me only 12

I need it.

my $number = 12.345673412;
printf( "%.3f\n", $number); 

such a basic question cannot be that urgent. Sounds like homework.

Ok. But i want to store the result into that variable.

  1. I think you might want to read some perl documentation or a perl book - most especially if this is something you are doing for your work.

  2. my $var = sprintf("%.3f", 12.123456);

my $var = sprintf("%.3f", $number);

perldoc -f sprintf

Thanks :slight_smile:

$number=~ s/([^\.]*\.)(...).*/$1$2/;

---------- Post updated at 01:30 AM ---------- Previous update was at 01:14 AM ----------

You can also use:

$number=~ s/(\d*\.)(\d{0,3}).*/$1$2/;

No, that does not do any rounding off. If all you wanted to do was truncate the number of digits then substr() is better for that unless you had to search for the number in a string.

Generic, works in every language:

$number=int($number*1000)/1000;

Hi Kelvin !

I suggested so, as asked by pritish.

Do you have a question?