Python Forum

Full Version: formatting float like int for whole values
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i know i have seen this before but now that i have a use case, i can't find it.
Output:
>>> foo(3.25) '3.25' >>> foo(4.0) '4' >>>
i want to find what works like foo() in this fake example.
i thought i had seen it as a single function. i want to do this in an f-string. i want to keep it simple. maybe it was something i had coded a long time ago like answer #3 in that link.
Something like this perhaps.
def foo (floating_point_number) :
	integer = int (floating_point_number)
	if integer == floating_point_number :
		return integer
	return floating_point_number

print (f'{foo (3.25)}, {foo (4.0)}')
close to that. while str() isn't exactly necessary, that was what i had in mind ... that foo() did the formatting.
def foo (floating_point_number) :
    integer = int (floating_point_number)
    if integer == floating_point_number :
        return str(integer)
    return str(floating_point_number)

print (f'{foo (3.25)}, {foo (4.0)}')
Do you mean like this?
def foo (floating_point_number) :
	integer = int (floating_point_number)
	if integer == floating_point_number :
		print (integer)
	else :
		print (floating_point_number)

foo (3.25)
foo (4.0) 
not to print in the function since i may want 2 or more on the same line. i may or may not need a str returned.
You said that you want this:
Output:
>>> foo(3.25) '3.25' >>> foo(4.0) '4' >>>
and I gave you this:
Output:
>>> def foo (floating_point_number) : ... integer = int (floating_point_number) ... if integer == floating_point_number : ... return integer ... return floating_point_number ... >>> foo (3.25) 3.25 >>> foo (4.0) 4 >>>
The only difference I see is the quotation marks. Is that what your looking for? If not, can you explain exactly what the difference is?
The difference is return a string, not a number. I think Skaperen wants something that returns the shortest string that accurately represents the value of a number.