October 2006
Intermediate to advanced
888 pages
16h 55m
English
Kirk: What would you say the odds are on our getting out of here?
Spock: It is difficult to be precise, Captain. I should say approximately 7824.7 to one.
—Star Trek, “Errand of Mercy”
If you want to round a floating point value to an integer, the method round will do the trick:
pi = 3.14159 new_pi = pi.round # 3 temp = -47.6 temp2 = temp.round # -48
Sometimes we want to round not to an integer but to a specific number of decimal places. In this case, we could use sprintf (which knows how to round) and eval to do this:
pi = 3.1415926535
pi6 = eval(sprintf("%8.6f",pi)) # 3.141593
pi5 = eval(sprintf("%8.5f",pi)) # 3.14159
pi4 = eval(sprintf("%8.4f",pi)) # 3.1416Of course, this is somewhat ugly. Let’s encapsulate ...
Read now
Unlock full access