【问题标题】:Checking if a float is an integer in Python在 Python 中检查浮点数是否为整数
【发布时间】:2013-12-26 21:59:15
【问题描述】:

我正在画布上绘制图形并插入画布文本对象以标记 x 和 y 轴间隔。

这是我的代码。

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)

这会根据输入的比例绘制所有间隔。

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

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

这决定了 x 和 y 轴上每个刻度的比例,并将其乘以 5 以获得每五个刻度的值。有 25 个刻度,所以我将输入除以/25。

我想显示这些值,但它们都是浮点数。如果它们是真正的整数,我想在没有 .00s 的情况下显示它们(我有 %.1f 将其限制为小数点后 1 位),如果它们实际上是浮点数而不是附有 .00s 的整数,则显示它们最多 2 个小数。有没有办法做到这一点?

编辑 1: 例如,刻度为 25,因此每个刻度为 1。第五个刻度将为 -10.0、-5.0、5.0、10.0、15.0 等。 我希望它显示 10、5、15 等,但如果是 0.5、1.0、1.5、2.0 我想保留所有小数,但真正的整数(如 1.0 和 2.0)将变为 1 和 2。

谢谢!

【问题讨论】:

标签: python floating-point int


【解决方案1】:

python浮点型中有is_integer函数:

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

【讨论】:

    猜你喜欢
    • 2011-08-13
    • 2013-11-29
    • 2013-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 2015-12-24
    相关资源
    最近更新 更多