SpectrumUSR
Posts: 7
Joined: Tue Feb 05, 2013 11:32 am

How do I Round Numbers ?

Wed Mar 27, 2013 10:28 pm

Ok the story so far, using IDLE 2 or IDLE 3

If I include the line Import math at the start of the program

I can use math.sqrt( x) # to get the Square root of x

So is there a Round function I can use to clean up the answer to
One decimal place ?

Eg convert 15.634719 .... to 15.6 # turns of wire thro a Powered Iron core .
I have looked in Raspberry Pi users guide Not found the answer!

In GFA v3 for the ATARI
I could use ROUND (x,1) Function
So
What do I use in IDLE 2 or IDLE 3

Thanks de John.

User avatar
joan
Posts: 14935
Joined: Thu Jul 05, 2012 5:09 pm
Location: UK

Re: How do I Round Numbers ?

Wed Mar 27, 2013 11:06 pm

Write your own function.

To round to one decimal place add 0.05, multiply by 10, take the integer value, then divide by 10.

DirkS
Posts: 10363
Joined: Tue Jun 19, 2012 9:46 pm
Location: Essex, UK

Re: How do I Round Numbers ?

Thu Mar 28, 2013 12:04 am

According to the docs Python has the same function: http://docs.python.org/2/library/functions.html#round

Gr.
Dirk.

SpectrumUSR
Posts: 7
Joined: Tue Feb 05, 2013 11:32 am

Re: How do I Round Numbers ?

Thu Mar 28, 2013 10:27 am

Thanks for the Help in sorting that out.

How I thought the Function would work was:

The same as turns=math.sqrt(turns)... To find the square root.

So I tried
turns=math.round(turns,1). ... Which did'nt work came up with error

turns=round(turns,1). Works thanks Dirk and Joan.

John.

User avatar
Redrobes
Posts: 80
Joined: Mon Dec 26, 2011 9:19 pm
Location: S.W. UK
Contact: Website

Re: How do I Round Numbers ?

Thu Mar 28, 2013 2:22 pm

I agree with joan's answer which is perfect for this case of sqrt.

But for the case where people may come across this thread for something else and the numbers to be rounded can be negative then you need to sort that out first.

Something like this:

if( num < 0 )
{
pos = -num;
pos += 0.05
pos *= 10
pos = (int)pos
num = -pos / 10
}
else
{
pos += 0.05
pos *= 10
pos = (int)pos
num = pos / 10
}

Return to “General programming discussion”