I want a variable code which rounds for example 0.91823 to 0.92 , but the number 0.00009384 should be rounded to 0.000094. I guess it's easy, but I could not find something which does the job.
Asked
Active
Viewed 115 times
3 Answers
2
For clarity I'll keep the code expanded, rather than forcing it into a one-liner.
def round2(n, numberOfDigits):
p = floor(log10(n));
# normalize
n = n * pow(10, -p);
# round
n = (n - n % pow(10, numberOfDigits)) * pow(10, p);
# return
return n;
The idea is to first 'remove' all leading zeroes by multiplying the incoming number by an appropriate power of 10. Then use the normal rounding operator to round the new number to the appropriate radix. And finally scale the number again.

Joris Schellekens
- 8,483
- 2
- 23
- 54
-
I think you want `pow(10, 1 - numberOfDigits)` instead of `pow(10, numberOfDigits)`. (For the OP's use-case of rounding to 2 digits, you need to use `numberOfDigits=-1` with the current code.) – Mark Dickinson Nov 20 '18 at 18:57
1
You can print the number to 2 digits of precision, then convert back to a float by specifying the required number of decimal places:
# Format the number to scientific notation with one digit before
# the decimal point and one after, then split the sctring into the mantissa
# and exponent.
a, b = ('{0:.1E}'.format(.0000004565)).split("E")
# If the exponent is -n, get the number of required decimal digits as n+1.
c=1-int(b)
# Set up a '%0.xf' format string where x is the required number of digits,
# and use that format to print the reassembled scientific notation value
res = ('%%0.%df' % c) % float(a+"E"+b)
This works with some numbers >1, but breaks down above 99.

simon3270
- 722
- 1
- 5
- 8
0
You could try string-manipulation:
import re
def roundToDigit(number, numDigits):
# Convert number to a string
asStr = str(number)
# Search for the first numerical digit, ignoring zeros
m = re.search("[123456789]", asStr)
if (not m):
return round(0, numDigits)
afterDecimal = m.start()
# Check if the number is in scientific notation
isExp = asStr.find("e") > -1
if (isExp):
numZeros = int(asStr[ (asStr.find("-", 1) + 1) :])
return float(round(number, numZeros + numDigits - 1))
# Check for numbers > 9
beforeDecimal = asStr.find(".")
if (beforeDecimal == -1):
return float(round(number, numDigits))
return float(round(number, afterDecimal - beforeDecimal + numDigits - 1))
Using log
is probably the correct choice but if, for whatever reason, that doesn't do it for you then this will work.

Woody1193
- 7,252
- 5
- 40
- 90