Reputation: 87
My code tries to convert a number to for example X meter Y centimeter and Z milimeter.My code works correctly for numbers with out any zero like 5782 but when it comes to numbers with zero it will not work properly
This is my code :
a = 2200
b = a / 1000
print(float(b))
b = str(float(b)).split(".")
first = b[0]
print(first,b[1])
c = (float(b[1])/10)
print(c)
c = str(c).split(".")
print(c)
second = (c[0])
third = (c[1])
print("%s Meter %s centimeter %s milimeter"%(first,second,third))
The result has to be like 2 meter 20 centimeter 0 milimeter but it gives me 2 meter 0 centimeter 2 milimeter
How can i solve that guys?
Upvotes: 1
Views: 1084
Reputation: 51683
You use integer division:
print( 27 // 4 ) # prints 6 because 6*4 = 24 and 7*4 is too big
With integer division you get how many "full" meters are in 2200mm (2) and then you substract 2*1000 from the mm
value, continue with cm
and whats left over are mm
.
mm = 2200 # startvalue in mm
m = mm // 1000 # how many full meters in mm?
mm -= m*1000 # reduce mm by amount of mm in full meters
cm = mm // 10 # how many full centimeter in mm?
mm -= cm*10 # reduce mm by amount of mm in full centimeters
print(f"{m} meter {cm} centimeter {mm} millimeter")
Ouput:
2 meters 20 centimeter 0 millimeter
If you want to omit a zero value you would need conditional printing:
if m != 0:
print(f"{m} meter ", end="")
if cm != 0:
print(f"{cm} centimeter ", end="")
if mm != 0:
print(f"{mm} millimeter", end="")
print() # for the newline
Upvotes: 2
Reputation: 2517
You really, really, really shouldn't use int
to str
conversion and the split
method to remove decimals...
So, what I see you are doing is millimeters to meters, centimeters, and millimeters. What I would do is use math.floor
to remove the decimal places -
import math
a = 2200
meters = math.floor(a / 1000)
centimeters = math.floor((a - meters * 1000) / 10)
millimeters = math.floor(a - meters * 1000 - centimeters * 10)
print(meters, centimeters, millimeters)
Upvotes: 2