Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic

Rounding with sprintf and -0

by johnfl68 (Beadle)
on Apr 07, 2013 at 01:05 UTC ( #1027317=perlquestion: print w/replies, xml ) Need Help??
johnfl68 has asked for the wisdom of the Perl Monks concerning the following question:


I am using sprintf to round temperatures.

my $temperature = sprintf("%.0f", $temperature);

Nothing fancy, and it works fine for what I want, with one exception.

If the temperature is greater than -0.50 but less than 0.00, using sprintf gives -0, but I want just 0.

Right now I just added a if/then to change -0 to 0, but is there a simpler way?

So far in looking I have not found anything, but then some of you know some little tricks, so I figure it doesn't hurt to ask.



Replies are listed 'Best First'.
Re: Rounding with sprintf and -0
by Loops (Curate) on Apr 07, 2013 at 02:04 UTC
    Maybe this works for ya:
    use feature 'say'; say int(-0.2 + 0.5); # 0 say int(3.49 + 0.5); # 3 say int(3.50 + 0.5); # 4
    Check out this thread for lots of options: How do I round a number?.
Re: Rounding with sprintf and -0
by Anonymous Monk on Apr 07, 2013 at 01:41 UTC

      Hmmm - I replied to this earlier, but now it is gone?

      To Anonymous Monk - Thank you! As soon as I read add +0 it made total sense.


Re: Rounding with sprintf and -0
by Khen1950fx (Canon) on Apr 07, 2013 at 06:55 UTC
    Since you just want an unsigned 0, use %u and String::Sprintf:
    #!/usr/bin/perl -l use strict; use warnings; use String::Sprintf; my $formatter = String::Sprintf->formatter( F => sub { my($width, $value, $values, $letter) = @_; my $s = sprintf "%${'width'}f", $value; $s =~ s/\.?0*$//; return $s; } ); print $formatter->sprintf( "%u", -0.5 );

      and String::Sprintf:

      No Khen1950fx , even sprintf has %u, not that you need to sprintf twice

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1027317]
Approved by ww
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (8)
As of 2018-07-16 18:31 GMT
Find Nodes?
    Voting Booth?
    It has been suggested to rename Perl 6 in order to boost its marketing potential. Which name would you prefer?

    Results (346 votes). Check out past polls.