简体   繁体   English

将截断的 Python 浮点数格式化为字符串中的 int

[英]Format truncated Python float as int in string

A quick no-brainer:一个快速的头脑:

some_float = 1234.5678
print '%02d' % some_float  # 1234

some_float = 1234.5678
print '{WHAT?}'.format(some_float) # I want 1234 here too

Note: {:.0f} is not an option, because it rounds (returns 1235 in this example).注意: {:.0f}不是一个选项,因为它会四舍五入(在本例中返回1235 )。

format(..., int(some_float)) is exactly the thing I'm trying to avoid, please don't suggest that. format(..., int(some_float))正是我想要避免的事情,请不要建议这样做。

It's worth mentioning the built in behavior for how floats are rendered using the raw format strings.值得一提的是关于如何使用原始格式字符串呈现浮点数的内置行为。 If you know in advance where your fractional part lies with respect to 0.5 you can leverage the format string you originally attempted but discovered it fell short from rounding side effects "{:0.0f}" .如果您事先知道小数部分相对于 0.5 的位置,您可以利用您最初尝试的格式字符串,但发现它没有舍入副作用"{:0.0f}" Check out the following examples...看看下面的例子...

>>> "{:0.0f}".format(1.999)
'2'
>>> "{:0.0f}".format(1.53)
'2'
>>> "{:0.0f}".format(1.500)
'2'
>>> "{:0.0f}".format(1.33)
'1'
>>> "{:0.0f}".format(0.501)
'1'
>>> "{:0.0f}".format(0.5)
'0'
>>> "{:0.0f}".format(0.1)
'0'
>>> "{:0.0f}".format(0.001)
'0'

As you can see there's rounding behavior behind the scenes.如您所见,幕后存在舍入行为。 In my case where I had a database converting ints to floats I knew I was dealing with a non fractional part in advance and only wanted to render in an html template the int portion of the float as a workaround.在我有一个将整数转换为浮点数的数据库的情况下,我知道我正在处理一个非小数部分,并且只想在 html 模板中呈现浮点数的 int 部分作为解决方法。 Of course if you don't know in advance the fractional part you would need to carry out a truncation operation of some sort first on the float.当然,如果您事先不知道小数部分,则需要先对浮点数执行某种截断操作。

It's possible to extend the standard string formatting language by extending the class string.Formatter :可以通过扩展类string.Formatter来扩展标准字符串格式化语言:

class MyFormatter(Formatter):
    def format_field(self, value, format_spec):
        if format_spec == 't':  # Truncate and render as int
            return str(int(value))
        return super(MyFormatter, self).format_field(value, format_spec)

MyFormatter().format("{0} {1:t}", "Hello", 4.567)  # returns "Hello 4"

This works:这有效:

from math import trunc
some_float = 1234.5678

print '{:d}'.format(trunc(some_float))
=> 1234

Or just do this, for that matter:或者就这样做,就此而言:

print trunc(some_float)
=> 1234

I think it's an acceptable answer, it avoids the conversion to int .我认为这是一个可以接受的答案,它避免了转换为int Notice that in this snippet: '%02d' % some_float an implicit conversion to int is happening, you can't avoid some sort of conversion for printing in the desired format.请注意,在此代码段中: '%02d' % some_float正在发生向int的隐式转换,您无法避免以所需格式打印的某种转换。

This will work too:这也将起作用:

some_float = 1234.5678
f = lambda x: str(x)[:str(x).find('.')]
print '{}'.format(f(some_float))
=> 1234

After doing a %timeit test it looks like this is a bit faster than the trunc method.进行 %timeit 测试后,看起来这比 trunc 方法快一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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