Python Forum
Round a number up to certain significant figures
Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Round a number up to certain significant figures
#4
import math
maxValue = 123 # maximum value
a = maxValue/4.0 # Python 2.x requires either numerator/denominator to be a float to return one
integerPart = str(a).split('.')[0] # if "a" is a decimal this selects the integer part
numberDigits = len(integerPart) # length of integerPart

def upperRound(x,N):
    return ((x+N/2) // N) * N

print "Maximum value = {}".format(maxValue)
print "Maximum value/4 = {}".format(a)
print "length of integer part = {}".format(numberDigits)
print upperRound(a, 10-numberDigits)
Output:
Maximum value = 123 Maximum value/4 = 30.75 length of integer part = 2 32.0
Maybe this is more of a mathematical question than Python. How can I amend the 2nd argument in upperRound such that the value returned from it for maxValue=1234 is bigger than Maximum value/4=308.5, as is the result if applied in this situation? 

Basically I want this script to be fully automated other than the maxValue being input by human, so for any maxValue/4, the output from upperRound should be bigger.
Reply


Messages In This Thread
RE: Round a number up to certain significant figures - by brocq_18 - Apr-06-2017, 06:13 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Adding Decimals to classes with OOP + rounding to significant digits (ATM demo) Drone4four 7 2,397 May-04-2022, 06:15 AM
Last Post: Drone4four
  Most optimized way to merge figures from multiple PDFs into one PDF page? dmm809 1 2,094 May-22-2019, 10:32 PM
Last Post: micseydel
  Cant get my head round the algorithm hshivaraj 1 2,365 Apr-09-2019, 10:38 PM
Last Post: Yoriz
  Unexpected round behavior pythonCoder 1 2,309 Feb-19-2019, 02:39 PM
Last Post: marienbad
  Add parameter to math.floor() to round to specific decimal point gabrield 2 2,751 Mar-09-2018, 08:43 PM
Last Post: wavic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020