Search code examples
pythonfloating-pointdecimalroundingtruncate

How to truncate a floating number to a number of decimals in Python?


I am a beginner in Python Learning

And I know that this rounds the number instead of truncating:

number_float = 14.233677
print(f"{number_float:.3f}")

=>This is printing 14.234, BUT I want 14.233

What other function can I use or how can I format this so as it won't round my number?

I tried with this format :.3f and i know it is wrong


Solution

  • You can use the math module,try this:

    import math
    
    number_float = 14.233677
    decimal_places = 3
    
    truncated_number = math.floor(number_float * 10**decimal_places) / 10**decimal_places
    print(truncated_number)