python - 在 Python 中检查 float 是否为整数

标签 python floating-point int

我在 Canvas 上绘制图形并插入 Canvas 文本对象以标记 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。

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

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

谢谢!

最佳答案

is_integer python float 类型的函数:

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

关于python - 在 Python 中检查 float 是否为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20476617/

相关文章:

java - 尝试从java中的JSON文件读取整数

python - 使用 `or` 会不会是 Pythonic,类似于 PHP 使用 `or die()` 的方式?

php - 接受包含多点系统的值

c# - 在 C# 中将科学计数法字符串转换为 float

opengl - `GLfloat` 和 `cl_float` 是否保证具有相同的大小?

c++ - 循环计数的有符号值与无符号值

java - 如何对整数循环数组执行左移?

python - tensorflow 中具有权重衰减参数的 SGD

python - systemd中pyenv下的jupyter笔记本仅提供系统python

python - 按时间排序列表中的文件,无法在列表中找到文件