[Tutor] Rounding Floating Points

Michael P. Reilly arcege@shore.net
Mon, 31 Jan 2000 22:46:10 -0500 (EST)


> I'm looking to round off a floating point number and then convert it to a
> string. I've accomplished this with the following in Perl:
> 
> $output_label2_var = sprintf("%.2f", $output_label2_var);
> 
> but have yet to find any reference to sprintf() in any my Python
> books/references or any other means of getting the same results for that
> matter. How would I go about accomplishing this in Python?

It seems you are just concerned with string formatting, not actual
rounding in a mathematical sense (which Perl doesn't have per se).
There is no sprintf function in Python because Python deals with string
formatting as an operator (like "+" or "*").

What you probably want is, resulting in a string instead of a number:
  output_label2_var = '%.2f' % output_label2_var

For example:
>>> '%.2f' % 4.506
'4.51'
>>>

But if you mean rounding functionality (the Perl Cookbook actually has
the laughable solution of using sprintf for rounding), then there is a
builtin function called round(), which will do this for you:
  output_label2_var = str(round(output_label2_var, 2))

>>> round(4.506, 2)
4.51
>>>

This rounds the value to the given decimal (by hundredths since that is
what you specify in your code) and converts the result to a string,
which is what the Perl code is doing.

Also, if you know a string is a float, you can convert the string with
the builtin function: float(), or the string module function atof().
Buf if you were dealing with numbers anyway, then don't worry about
using the string formatting or str() and float() functions.

Hope this helps,
  -Arcege

-- 
------------------------------------------------------------------------
| Michael P. Reilly, Release Engineer | Email: arcege@shore.net        |
| Salem, Mass. USA  01970             |                                |
------------------------------------------------------------------------