Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Rounding with sprintf and -0

by johnfl68 (Scribe)
on Apr 07, 2013 at 01:05 UTC ( [id://1027317]=perlquestion: print w/replies, xml ) Need Help??

johnfl68 has asked for the wisdom of the Perl Monks concerning the following question:

Hello:

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.

Thanks!

John

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.

      John

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?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1027317]
Approved by ww
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (4)
As of 2024-03-28 22:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found