Perl trim decimal number

This is a function to trim a decimal number in Perl, this function did not round the number just make an sub string from the dot to the end:

use strict;

print trim_deciamal("2.1",3).$/;
print trim_deciamal("2.12",3).$/;
print trim_deciamal("2.123",3).$/;
print trim_deciamal("2.1234",3).$/;
print trim_deciamal("2.12345",3).$/;

sub trim_deciamal{
my ($f,$h) = split(/\./o,$_[0]);
if(length($h) >= $_[1]){
    $h = substr($h,0,$_[1]);    
}else{
    $h = sprintf("%-".$_[1]."s",$h);
    $h =~ tr/ /0/;
}
return($f.".".$h);
}

Result looks like this:

2.100 
2.120 
2.123 
2.123 
2.123

we see missing positions are filled with 0 and longer numbers are trimmed.

2 thoughts on “Perl trim decimal number”

  1. Hi! I could have sworn I’ve been to this blog before but after browsing
    through some of the post I realized it’s new to me.
    Anyways, I’m definitely glad I found it and I’ll be bookmarking and checking back
    frequently!

Leave a Reply

Your email address will not be published.

11 + 14 =