convert.py: metres -> feet + inches (whole in, round-half-up)

This commit is contained in:
sisyphe committed 2026-10-03 22:51:47 +00:00
commit bf1f05f110
1 file changed
+32
Executable
+32
View File
@@ -0,0 +1,32 @@
#!/usr/bin/env python3
"""Convert a length in metres to feet and inches (whole inches, round-half-up)."""
import sys
IN_PER_M = 1.0 / 0.0254 # 1 in = 0.0254 m exactly
def m_to_ft_in(m: float) -> tuple[int, int]:
total = int(m * IN_PER_M + 0.5) # round-half-up on total inches
return total // 12, total % 12
def main(argv):
if len(argv) != 2:
sys.stderr.write("usage: convert.py <metres>\n")
return 1
raw = argv[1].rstrip("mM")
try:
m = float(raw)
except ValueError:
sys.stderr.write(f"error: '{argv[1]}' is not a number\n")
return 1
if m < 0:
sys.stderr.write("error: length must be non-negative\n")
return 1
ft, inch = m_to_ft_in(m)
print(f"{ft} ft {inch} in")
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))