Archived
33 lines
832 B
Python
Executable File
33 lines
832 B
Python
Executable File
#!/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))
|