Rounding numbers in Perl and saving to a variable

Many times I wanted to round a number in Perl and store it to a variable. Many web pages will teach how to round using printf, but then you can only print the rounded number.

But now, I found this very clever and simple way of rounding numbers in Perl.

It’s interesting to note that there are whole libraries that do the job (Math::Round), but one simple internal Perl function does it too.

$rounded = sprintf “%.1f”, $float;

That’s it.

Thanks to this page.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s