From 935103b79379fed1eb5cceaf6b439a843a087bb1 Mon Sep 17 00:00:00 2001 From: jay23606 <4602056+jay23606@users.noreply.github.com> Date: Fri, 20 Nov 2026 20:16:10 -0500 Subject: [PATCH] Add --decimals option to convert command (default 2) --- fixit/cli.py | 5 ++++- tests/test_cli.py | 21 +++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/fixit/cli.py b/fixit/cli.py index 8a99931..a331f2b 100644 --- a/fixit/cli.py +++ b/fixit/cli.py @@ -59,7 +59,7 @@ def run_wc(args: argparse.Namespace) -> None: def run_convert(args: argparse.Namespace) -> None: try: result = CONVERSIONS[args.kind](args.value) - print(result) + print(round(result, args.decimals)) except KeyError: raise ValueError(f"Error: unknown conversion '{args.kind}'") @@ -222,6 +222,9 @@ def build_parser() -> argparse.ArgumentParser: cv = sub.add_parser("convert", help="convert units") cv.add_argument("value", type=finite_float) cv.add_argument("kind", choices=sorted(CONVERSIONS)) + cv.add_argument( + "--decimals", type=int, default=2, help="digits after the decimal point (default: 2)" + ) pw = sub.add_parser("password", help="generate a password") pw.add_argument("--length", type=int, default=12) diff --git a/tests/test_cli.py b/tests/test_cli.py index bb9bf91..272ecc8 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -114,6 +114,27 @@ def test_roman_invalid_numeral(capsys): assert "not a valid Roman numeral" in capsys.readouterr().err +def test_convert_rounds_to_two_decimals_by_default(capsys): + result = main(["convert", "100", "f2c"]) + + assert result == 0 + assert capsys.readouterr().out.strip() == "37.78" + + +def test_convert_decimals_option(capsys): + result = main(["convert", "100", "f2c", "--decimals", "4"]) + + assert result == 0 + assert capsys.readouterr().out.strip() == "37.7778" + + +def test_convert_whole_result_keeps_trailing_zero(capsys): + result = main(["convert", "100", "c2f"]) + + assert result == 0 + assert capsys.readouterr().out.strip() == "212.0" + + @pytest.mark.parametrize("value", ["nan", "inf"]) def test_convert_rejects_non_finite_values(value): with pytest.raises(SystemExit):