If you know that your result will always be:<br><br>X.Y<br><br>i.e. one digit before and another after the decimal point...<br><br>use:<br><FONT FACE=monospace>print "%1.1f", $num;</font><br><br>or if you don't know how many digits before the point you want:<br><br><FONT FACE=monospace><br>$num = 3.5675737;<br><br>($before,$after) = split(/\./,$num);<br>$before = length $before;<br><br>printf "%$before.1f" , $num;<br></font><br><br>Hope that helps<br>Loon
Ok, but I have to add together the rounded answers. I need to print 3.6 but also need to add 3.6 to something else.<br><br>Is there something to round it and still be able to add them together? <br><br>Will what you gave me be able to do that?
The printf doesn't change the value of the scalar no.. it's still 5.56737 etc..<br><br>I'm sure there'll be a way to do it - unfortunately I have no idea how, I suspect there's a CPAN module for this kind of thing somewhere.<br><br>Failing that, could you do the arithmetic first and then round out for the printing at the end?<br><br>Good luck!<br>Loon
There's a companion to the printf function that you can use to format a value, and assign that value to another scalar: sprintf. Here's a quick example:<br><FONT FACE=monospace><br>$Value = 3.141579; # Whatever ;^)<br><br>$Rounded = sprintf("%1.1f", $Value);<br><br>print "Original: ", $Value, "\n";<br>print "Rounded: ", $Rounded, "\n";<br></font> <p> <br><a href=mailto: > </a><br><a href= > </a><br>--<br>
0 1 - Just my two bits
Errmm - don't printf and sprintf just truncate the values - as opposed to rounding them? <p>Mike<br><a href=mailto:michael.j.lacey@ntlworld.com>michael.j.lacey@ntlworld.com</a><br><a href=
They round, but slightly differently from what you may be used to. (At least in the quick test I just did <br><br>For example: 0.01 to 0.50 will display as 0.<br><br>0.51 to 0.99 will display as 1.<br><br>0.123 with a format of %1.1f will display as 0.1, as will 0.126. (This gives you 0.13 which in turn rounds down to 0.1.)<br><br>I was always taught that 0.5 and about should round up, but perl seems to do it as anything over 0.5 will round up... <p> <br><a href=mailto: > </a><br><a href= > </a><br>--<br>
0 1 - Just my two bits
Ok - that sounds like reasonable behaviour - I'll bear it in mind, thanks Andy. <p>Mike<br><a href=mailto:michael.j.lacey@ntlworld.com>michael.j.lacey@ntlworld.com</a><br><a href=
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.