Python Forum
print either int or float - How?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
print either int or float - How?
#1
Hello

I want to print number as whole if there is no decimal point and if there is decimal point, then print with decimal point.

For example,

length = float(input("Enter length: "))
width = float(input("Enter width: "))
total = length * width
print(f"The area of {length}x{width} is {total}")
The o/p be like

Output:
Enter length: 30 Enter width: 50 The area of 30.0x50.0 is 1500.0
OR

Output:
Enter length: 25 Enter width: 35.5 The area of 25.0x35.5 is 887.5
I want the output to be in whole number if there are no decimal points and in float if there are decimal points, like the following
Output:
The area of 30x50 is 1500 The area of 25x35.5 is 887.5
How do I format my print statement? Is that even possible?

Thanks
Reply
#2
There are several approaches:
e.g. you can test the variable for it's "type".
a = 3.5
b = 5
if type(a) == float:
    print(a)
if type(b) == int:
    print(b)
or you could do
if int(b) == b:
    print(int(b))
Paul
It is more important to do the right thing, than to do the thing right.(P.Drucker)
Better is the enemy of good. (Montesquieu) = French version for 'kiss'.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  python calculate float plus float is incorrect? sirocawa 6 322 Apr-16-2024, 01:45 PM
Last Post: DeaD_EyE
  Comaparing Float Values of Dictionary Against A Float Value & Pick Matching Key firebird 2 3,403 Jul-25-2019, 11:32 PM
Last Post: scidam
  Unable to print the exact Float values when I convert LIST to Sequence of Tuples? preethamalluri 1 2,444 Jul-12-2018, 09:03 AM
Last Post: buran
  Outputting a float value in a print() statement RedSkeleton007 2 3,536 Jan-11-2018, 09:23 AM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020