Python Forum

Full Version: How to trim a float number?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Does anyone know how to trim / clip a float number?

I'm printing out a lot of numbers to my shell window and would like to trim float numbers. I had a quick look at the built in routines but can't remember how to do it. I created a little routine and was wondering if this was the best way to get it done. I'm hoping someone has a better way.

def mytrim(float_number, length =2):
    if isinstance(float_number, float):
        num =str(float_number)
        digits =num.split(".")
        return_str =digits[0] +"." +str(digits[1])[:length]

        return return_str
# mytrim() ------------------------------------------------------------------
    
print(mytrim(328.88452), mytrim(31.11547999999999))
Output:
328.88 31.11
String formatting?
>>> some_num = 328.88452
>>> some_other_num = 31.11547999999999
>>> print("{:.2f}, {:.2f}".format(some_num, some_other_num))
328.88, 31.12
>>>
Thanks Mekire, that's just what I was looking for.
There is also format() option:

>>> format(31.11547999999999, '.2f')
'31.12'
(Aug-20-2018, 07:49 PM)perfringo Wrote: [ -> ]There is also format() option:
Yes,but is more rarely used.

I use f-string in all do since 3.6 came out.
Use format() sometime on forum,because not all use 3.6 or 3.7.
>>> some_num = 328.88452
>>> some_other_num = 31.11547999999999
>>> print(f"{some_num:.2f}, {some_other_num:.2f}")
328.88, 31.12
(Aug-20-2018, 08:22 PM)snippsat Wrote: [ -> ]
(Aug-20-2018, 07:49 PM)perfringo Wrote: [ -> ]There is also format() option:
Yes,but is more rarely used.

It may be so. However, OP-s question was not about rarity or ordinarity. It's just one way of doing it.

There is "that's just what I was looking for" from OP, however it's fair to mention that no solution provided actually meets initial requirements. Example output is 31.11 but .2f in whichever flavour returns 31.12.