[Tutor] Rounding to n significant digits? (original) (raw)
Alan Gauld alan.gauld at blueyonder.co.uk
Fri Jul 2 03:05:07 EDT 2004
- Previous message: [Tutor] Rounding to n significant digits?
- Next message: [Tutor] Rounding to n significant digits?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Is there something (a function?) in Python 2.3.4 that will round a result to n significant digits, or do I need to roll my own? I don't see one in the math module.
the round() function is a builtin.
I mean something like rounding(float, n) that would do this: float = 123.456789, n = 4, returns 123.5
round(123.45678,3) 123.45699999999999
Note that this will result in a new floating point number, that is you actually lose data in the process. (Which is why it prints out with more than 3 digits - it is a float with all the usual imprecision issues that floats have). "print"ing it instead of evaluating it will give the expected result of course:
print round(123.45678,3) 123.457
If you just want to display the number at a given precision but to keep the original accuracy internally use a format string instead.
print "%6.3f" % 123.456789 123.457
And of course this creates a string rounded to the nearest digit rather than a floating point number.
Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld
- Previous message: [Tutor] Rounding to n significant digits?
- Next message: [Tutor] Rounding to n significant digits?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]