TDT4109/Exercise 1/11 - James Bond and Operati.../11-a.py

29 lines
946 B
Python

import math
from common import inputTypeCheck
# Bump the decimal point up by numberOfDecimal points,
# add 0.5 to make floor go from 0-1 to 0.5-1.5,
# then add back the decimal points.
def myRoundFunction(number, numberOfDecimals):
decimalFactor = 10 ** numberOfDecimals
return math.floor(number * decimalFactor + 0.5) / decimalFactor
def removeEmptyDecimals(number):
hasEmptyDecimals = (number == int(number))
return int(number) if hasEmptyDecimals else number
number = inputTypeCheck(
message='Gi inn et desimaltall: ',
type=float,
errorMessage='Beklager, det du skrev inn er ikke et nummer. Prøv igjen\n'
)
numberOfDecimals = inputTypeCheck(
message='Antall desimaler i avrunding: ',
type=int,
errorMessage='Beklager, det du skrev inn er ikke et heltall. Prøv igjen\n'
)
roundedNumber = removeEmptyDecimals(myRoundFunction(number,numberOfDecimals))
print(f'Avrundet til {numberOfDecimals} desimal: {roundedNumber}')