Skip to content Skip to sidebar Skip to footer

How Do I Make A Float Only Show A Certain Amount Of Decimals

I have a float that has 16 decimal places, but I want it to be capped at 6, and if I ever get a float that has less than 6 decimals, I want it to add 0s until it has 6. i.e.: 1.95

Solution 1:

To round to a certain amount of decimals you can use round()

Example:

round(1.95384240549,6) > 1.953842

And for more 0's after the decimal place you can use format():

format(3.12, '.6f') > '3.120000'

Note this is of type string

Read more here:

Rounding syntax

Format syntax

Solution 2:

A bit more complex than the previous answer, but more consistent.

import math

def truncate(number, digits) -> float:
    places = len(str(number)[str(number).find("."):])
    if places > 6:
        stepper = 10.0 ** digits
        return math.trunc(stepper * number) / stepper
    else:
        returnstr(number) + "0"*(6 - places)

Examples: truncate(3.12 , 6) returns 3.120000 and truncate(1.95384240549, 6) returns 1.953842

Post a Comment for "How Do I Make A Float Only Show A Certain Amount Of Decimals"