简体   繁体   中英

Checking if a float is an integer in Python

I'm drawing a graph on a canvas and inserting canvas text objects to label the x and y axis intervals.

here is my code.

def update():
    scalex1=graph.create_text(356,355-87,text='%.1f'%scalex,anchor=NW)
    scalex2=graph.create_text(412,355-87,text='%.1f'% (scalex*2),anchor=NW)
    scalex3=graph.create_text(471,355-87,text='%.1f'%(scalex*3),anchor=NW)
    scalex4=graph.create_text(532,355-87,text='%.1f'%(scalex*4),anchor=NW)

    scalenx1=graph.create_text(255-23,355-87,text='%.1f'%(scalex*-1),anchor=NW)
    scalenx2=graph.create_text(195-25,355-87,text='%.1f'% (scalex*-2),anchor=NW)
    scalenx3=graph.create_text(135-25,355-87,text='%.1f'%(scalex*-3),anchor=NW)
    scalenx4=graph.create_text(66-18,355-87,text='%.1f'%(scalex*-4),anchor=NW)


    scaley1=graph.create_text(326,234,text='%.1f'%scaley,anchor=NW)
    scaley2=graph.create_text(326,174,text='%.1f'% (scaley*2),anchor=NW)
    scaley3=graph.create_text(326,114,text='%.1f'%(scaley*3),anchor=NW)
    scaley4=graph.create_text(326,54,text='%.1f'%(scaley*4),anchor=NW)

    scaleny1=graph.create_text(326,354,text='%.1f'%(scaley*-1),anchor=NW)
    scaleny2=graph.create_text(326,414,text='%.1f'%(scaley*-2),anchor=NW)
    scaleny3=graph.create_text(326,474,text='%.1f'%(scaley*-3),anchor=NW)
    scaleny4=graph.create_text(326,534,text='%.1f'%(scaley*-4),anchor=NW)

This draws all the intervals depending on the inputted scale.

x2=float(x1.get())
y2=float(y1.get())

scalex=5.0*(x2/25.0)
scaley=5.0*(y2/25.0)

This determines the scale for each tick on the x and y axis and multiplies it by 5 to get the value for every fifth tick. There are 25 ticks so i divide the input/25.

I want to display the values, but they all are floats. I would like to show them without .00s (I have %.1f to limit it to 1 decimal place) if they are truly integers and show them up to 2 decimals if they are actually floats and not ints with .00s attached. Is there a way to do this?

EDIT 1: For example, the scale is 25 so each tick is 1. The fifth ticks will be -10.0,-5.0,5.0,10.0,15.0 etc. I want it to display 10,5,15, etc. but if it is .5,1.0,1.5,2.0 I want to keep the decimals fo all but the true ints like 1.0 and 2.0 which will become 1 and 2.

Thanks!

There is is_integer function in python float type:

>>> float(1.0).is_integer()
True
>>> float(1.001).is_integer()
False
>>> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM