Coverage for install/scipp/utils/to_string.py: 77%
13 statements
« prev ^ index » next coverage.py v7.6.1, created at 2024-11-17 01:51 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2024-11-17 01:51 +0000
1# SPDX-License-Identifier: BSD-3-Clause
2# Copyright (c) 2023 Scipp contributors (https://github.com/scipp)
3# @file
4# @author Neil Vaytet
5from typing import Any
8def value_to_string(val: Any, precision: int = 3, max_str_len: int = 80) -> str:
9 """
10 Convert a number to a human-readable string.
11 """
12 if (not isinstance(val, float)) or (val == 0):
13 raw_text = str(val)
14 if len(raw_text) > max_str_len:
15 text = f"{raw_text[:max_str_len-3]}..."
16 else:
17 text = raw_text
18 elif (abs(val) >= 10.0 ** (precision + 1)) or (
19 abs(val) <= 10.0 ** (-precision - 1)
20 ):
21 text = "{val:.{prec}e}".format(val=val, prec=precision)
22 else:
23 text = f"{val}"
24 if len(text) > precision + 2 + (text[0] == '-'):
25 text = "{val:.{prec}f}".format(val=val, prec=precision)
26 return text