Calculate percentage then round

2672
6
Jump to solution
01-18-2016 09:13 AM
JudsonCrouch1
New Contributor III

I am very new to Python but need to write a script to add 20% to a field and then round that number with the 20% to the next 50. I have figured out the calculations but for the life of me can't figure out how to put them together to get it into one function.

I've tried this in the code block:

def boom_length(boom):
    twenty_percent = ((!LENGTH_FT!) * 0.2) + !LENGTH_FT!)
    math.ceil(twenty_percent + (50 - twenty_percent) % 50)
    return twenty_percent

then in the expression:

boom_length(!BOOM_LEN!)

Thanks in advance for the help!

0 Kudos
1 Solution

Accepted Solutions
XanderBakker
Esri Esteemed Contributor

...and to explain the reason for these changes:

  • you have to import math to be able to use it (I think)
  • The function will have no knowledge of the field !LENGTH_FT!, so you have to use the parameter "boom" instead
  • There were some problems with unpaired brackets
  • You have to assign the result of the math.ceiling to the variable you return or simply say:

return math.ceil(twenty_percent + (50 - twenty_percent) % 50)

View solution in original post

6 Replies
JoeBorgione
MVP Emeritus

I'm no python expert by any means but have you looked at the round() method?

http://stackoverflow.com/questions/17470883/how-to-round-to-two-decimal-places-in-python-2-7

That should just about do it....
0 Kudos
XanderBakker
Esri Esteemed Contributor

Try this:

def boom_length(boom):
    import math
    twenty_percent = boom * 0.2 + boom
    twenty_percent = math.ceil(twenty_percent + (50 - twenty_percent) % 50)
    return twenty_percent
XanderBakker
Esri Esteemed Contributor

...and to explain the reason for these changes:

  • you have to import math to be able to use it (I think)
  • The function will have no knowledge of the field !LENGTH_FT!, so you have to use the parameter "boom" instead
  • There were some problems with unpaired brackets
  • You have to assign the result of the math.ceiling to the variable you return or simply say:

return math.ceil(twenty_percent + (50 - twenty_percent) % 50)

JudsonCrouch1
New Contributor III

I think this is on the right track but it does not pull the value to add 20% to from the field "LENGTH_FT". My mistake...I should have mentioned that in the original post. I need it to pull a value from the field "LENGTH_FT", add 20% to it, then round that number up to the nearest 50 and store it in the field "BOOM_LEN"

0 Kudos
XanderBakker
Esri Esteemed Contributor

Assign the ouput to the field !BOOM_LEN!, but use the field !LENGTH_FT! as parameter in the expression:

in the expression:

boom_length(!LENGTH_FT!)

0 Kudos
JudsonCrouch1
New Contributor III

Thanks for the help! I was thinking too much about it...simple solution.

0 Kudos