How can I format a number to 2 decimal places in Perl? -


what best way format number 2 decimal places in perl?

for example:

10      -> 10.00 10.1    -> 10.10 10.11   -> 10.11 10.111  -> 10.11 10.1111 -> 10.11 

it depends on how want truncate it.

sprintf %.2f format normal "round half even".

sprintf("%.2f", 1.555);  # 1.56 sprintf("%.2f", 1.554);  # 1.55 

%f floating point number (basically decimal) , .2 says print 2 decimal places.


if want truncate, not round, use int. since truncate integer, have multiply , divide again number of decimal places want power of ten.

my $places = 2; $factor = 10**$places; int(1.555 * $factor) / $factor;  # 1.55 

for other rounding scheme use math::round.


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -