User:Eleanorg/Prototyping Yr 1 Timester 1/Cookbook: Percentages

From XPUB & Lens-Based wiki

Fun with percentages, for the mathematically impaired!

Here are some examples of cool things you can do by grabbing numbers from the internet, and converting them into percentages. Once you've converted your number into a percentage, you can use it to determine CSS styles. (Conversion to % also has the added benefit of making your randomly scraped data seem "scientific".)


Converting to a % value

In this example, I have the longitudinal position of a ship. I want to turn its position into a percentage, based on its distance from its final destination. First, establish the ship's starting point (001.2528), and its destination (004.1285). These will act as 0% and 100% respectively. The percentage is worked out based on the ship's current position within this range.

Note how the data type changes several times in order to undergo the various manipulations necessary:

import re
 
### convert longitude into 5 digit integer
longitude = str(001.2528) 			# must be a string for regex to work
longint = int(re.sub("\.", "", longitude)) 	# removes decimal point and converts back to an integer
 
### convert integer into percentage of given range
# converts longitude into a percentage, where 001.2528 = 0% and 004.1285 = 100%
# range between numbers is 28703, so 1% of range is 28703/100 ---> 287.03. Longitude equivalent to 1% will be 12528 + (28703/100)
# thus to convert longitude to percentage, work out its distance from 12528 and divide this distance by 287.03.

percent = float(int((longint - 12528) / 287.03))
         ## now move decimal point two places left and convert to a string, for use with CSS
opacity = str(percent / 100)

Using % value in CSS Styling

CSS uses percentages in the format of floats (eg, 0.5 rather than 50%), and for concatenation with html, they must then be converted to a string (as in the example above).

Div size

Here, we use our % value to determine the size of a div in an html document:

print "Content-Type: text/html"
print
print """
  <html>
    <body>
       <div style="width:""" + percent + """%; height:""" + percent + """%; background-color: #ddd;">
         <p>""" + percent + """</p>
       </div>
    </body>
  </html>""

Image opacity

Here, we use the % value to change the opacity of an image.

print "Content-Type: text/html"
print
print """
  <html>
    <body>
       <div>
         <img src="foo.jpg" alt="an image of varying opacity" style="opacity:""" + percent + """;" />
       </div>
    </body>
  </html>"""