Coverage for nlp_manager/number.py: 87%
15 statements
« prev ^ index » next coverage.py v7.8.0, created at 2025-08-27 10:34 -0500
« prev ^ index » next coverage.py v7.8.0, created at 2025-08-27 10:34 -0500
1"""
2crate_anon/nlp_manager/number.py
4===============================================================================
6 Copyright (C) 2015, University of Cambridge, Department of Psychiatry.
7 Created by Rudolf Cardinal (rnc1001@cam.ac.uk).
9 This file is part of CRATE.
11 CRATE is free software: you can redistribute it and/or modify
12 it under the terms of the GNU General Public License as published by
13 the Free Software Foundation, either version 3 of the License, or
14 (at your option) any later version.
16 CRATE is distributed in the hope that it will be useful,
17 but WITHOUT ANY WARRANTY; without even the implied warranty of
18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 GNU General Public License for more details.
21 You should have received a copy of the GNU General Public License
22 along with CRATE. If not, see <https://www.gnu.org/licenses/>.
24===============================================================================
26**Number conversion functions.**
28"""
30from typing import Optional
33def to_float(s: str) -> Optional[float]:
34 """
35 Convert a string to a float, or return ``None``.
37 Before converting:
39 - strips out commas (as thousands separator); this is not internationalized
40 well!
41 - replace Unicode minus and en dash with a hyphen (minus sign)
42 """
43 if s:
44 s = s.replace(",", "") # comma as thousands separator
45 s = s.replace("−", "-") # Unicode minus
46 s = s.replace("–", "-") # en dash
47 try:
48 return float(s)
49 except (TypeError, ValueError):
50 return None
53def to_pos_float(s: str) -> Optional[float]:
54 """
55 Converts a string to a positive float, by using :func:`to_float` followed
56 by :func:`abs`. Returns ``None`` on failure.
57 """
58 try:
59 return abs(to_float(s))
60 except TypeError: # to_float() returned None
61 return None