Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Number formatting 2

Status
Not open for further replies.

deadpainter

Programmer
Apr 4, 2005
4
CA
Honestly, it's been a few years since I've used Perl, and it was never something I used on a regular basis. This is probably a simple question, although I am having issues finding an answer. I have the following calculation:

$temp = $myNum / 10;
$newNum = sprintf("%.0f\n",$temp);

The issue is that I need to format the number so that it does not round $newNum up, and I do not want a decimal number.

ie: if $temp = 26, I want $newNum = 2, not 3.

Any thoughts?
 
maybe just use substr() instead to get only the first digit from the string:

$temp = $myNum / 10;
$newNum = substr($temp,0,1);
 
Another way might be to use the floor() function in the POSIX module, or you can write one yourself. Something like this might work:

Code:
print &floor(26/10), "\n";

sub floor ($) {
    my $float = shift;
    substr($float,0,index($float, '.'));
}
 
Thanks for the tips, I will try them tonight. Much appreciated.
 
rharsh, while this isn't directly related to the OP's question, thought I'd point out that prototype checking is disabled if you call a sub with &. The prototype on the sub is useless here. See perldoc perlsub.

 
How about changing your format string so it gives you an integer instead of a float?
Code:
$temp = $myNum / 10;
$newNum = sprintf("%[b]d[/b]",$temp);

 
I used rharsh's code initially, and it worked beautifully. However, I ended up using mikevh's idea for the simplicity, not that any were complicated.

I feel slightly ashamed with the fact I didn't realize I was using a float rather than an int. It didn't even cross my mind to change it! Not too swift on my part.

But again, I thank you all for your help. It's not too often I post in a forum, and it's nice to know there are people around to lend a hand.

Thanks

<shaking head> 'A float...what was I thinking...'
 
mikevh, thanks for the info, I hadn't noticed that before. Have a star.
 
You can cast it to int.

Code:
$temp = int($myNum / 10);
 
After discovering (being shown) the whole float/int issue, I did indeed end up casting the the number as cyan01 showed.

Code:
$temp = int($myNum / 10);

Thanks again folks.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top