2

How to print 2.7 having 2.6000000000000001. (Or any other numbers like this).

import math

print(math.ceil(2.6000000000000001))  // 3
print(round(2.6000000000000001, 2))  // 2.6

???

2 Answers2

0
import math

num=2.6000000000000001
digits=1

t1=10**digits
math.ceil(num*t1)/t1
user0
  • 138
  • 1
  • 2
  • 6
0

If you want to do this in a generic way and for a different number of digits, here is an example on how to define yourself an according function:

import math

def round_decimals_up(number:float, decimals:int=1):
    if not isinstance(decimals, int):
        raise TypeError("decimal places must be an integer")
    elif decimals < 0:
        raise ValueError("decimal places needs to be 0 or more")
    elif decimals == 0:
        return math.ceil(number)

    factor = 10 ** decimals
    return math.ceil(number * factor) / factor

I adapted this to default to one decimal digit, but it also lets you specify the number of digits:

x = 2.6
y = 2.60000000001

print(round_decimals_up(x))
print(round_decimals_up(y))
print(round_decimals_up(x,2))
print(round_decimals_up(y,2))

yields

2.6
2.7
2.6
2.61
buddemat
  • 4,552
  • 14
  • 29
  • 49