Skip to content

Instantly share code, notes, and snippets.

@VietThan
Created May 22, 2023 18:11
Show Gist options
  • Save VietThan/1a1d389ceaab4542e87420b7e1b7ffc3 to your computer and use it in GitHub Desktop.
Save VietThan/1a1d389ceaab4542e87420b7e1b7ffc3 to your computer and use it in GitHub Desktop.
Set float up to a certain decimal point without rounding in Python
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