#-------------------------------------------------------------------------------
# Name:          Crop Number
# Purpose:       Limits decimal digits 
# Authors:       Eric N
#
# Last Version:  07.02.2022
# Copyright:     (c) Institute of Technical Biocatalysis TUHH
# Licence:       GNU GPL-v3 
#-------------------------------------------------------------------------------
import math

def cropNumber(self,number,nPositions):
        # Crops the size of a number (the sum of the positions before and after the decimal point) to nPositions.
        # Works only for numbers with less positions before the decimal point than nPositions''' 

        # checks whether the input is negativ and sets it positiv if so
        isPositiv = True
        if number < 0:
            isPositiv = False
            number = abs(number)
        # gets the decimal power of the input
        decPow = math.floor(math.log10(number))
        if number > 1:
            # checks the input
            if decPow > nPositions-1:
                print('Input number is to large!')
            # changes the decimal power of the input to 1 
            number = number/math.pow(10,decPow)
            # limits the positions after the decimal point to nPositions-1
            number = round(float(number),nPositions-1)
            # changes the number back to its original decimal power and original sign
            number = number*math.pow(10,decPow)
        else:
            # rounds numbers smaller than 1 to the corresponding amount of decimal places
            number = round(float(number),nPositions-1)
        if not isPositiv:
            number = number*(-1)
        #print(number)

        # floats will sometimes add further zeros and another digit to the end of a number.
        # The following will avoid this by formating the float
        if decPow > 0:
            format = "{:."+str(nPositions-1-decPow)+"f}"
        else:
            format = "{:."+str(nPositions-1)+"f}"
        number = float(format.format(number))
        return number