Search code examples
pythonfloating-pointnumbersroundingdecimal-point

limited float decimal point without rounding the number


I want convert a number to a float number with 3 decimal point but I want it without rounding. For example:

a = 12.341661
print("%.3f" % a)

This code return this number:

12.342

but I need to original number,I need this:

12.341

I write a code that receive a number form user and convert it to a float number. I have no idea that what is the number entered with user.


Solution

  • My first thought was to change print("%.3f" % a) to print("%.3f" % (a-0.0005)) but it does not quite work: while it outputs what you want for a=12.341661, if a=12.341 it outputs 12.340, which is obviously not right.

    Instead, I suggest doing the flooring explicitly using int():

    a = 12.341661
    b = int(a*1000)/1000.
    print(b)
    

    This outputs what you want:

    12.341
    

    To get 3 decimals out even if the input has fewer, you can format the output:

    a = 3.1
    b = int(a*1000)/1000.
    print("%.3f" % b)
    

    Outputs:

    3.100