Created
May 22, 2023 18:11
-
-
Save VietThan/1a1d389ceaab4542e87420b7e1b7ffc3 to your computer and use it in GitHub Desktop.
Set float up to a certain decimal point without rounding in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def truncate_float(f: float, n: int): | |
""" | |
Truncate float `f` to at most `n` decimal points. | |
- truncate_float(1.9333, 2) -> 1.93 | |
- truncate_float(1.9373, 2) -> 1.93 | |
- truncate_float(1.9, 2) -> 1.9 | |
https://stackoverflow.com/questions/29246455/python-setting-decimal-place-range-without-rounding | |
Parameters | |
---------- | |
f : float | |
the floating point number to be truncated | |
n : int | |
the number of decimals to be truncated to | |
Returns | |
------- | |
float | |
the truncated float | |
""" | |
return math.trunc(f * 10 ** n) / 10 ** n |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment