Sure, here's a Python function that uses the decimal module to round floating-point numbers half up to the specified precision:
python
from decimal import Decimal, ROUND_HALF_UP
def round_half_up(number, precision):
"""
Rounds a floating point number half up to the specified precision.
:param number: The floating point number to round.
:param precision: The number of decimal places to round to.
:return: The rounded number.
"""
# Convert the number to a Decimal, which allows for precise arithmetic.
decimal_number = Decimal(str(number))
# Define the rounding precision as a quantize exponent, e.g., '0.01' for 2 decimal places.
quantize_exp = Decimal('1').scaleb(-precision)
# Round the number half up.
rounded_number = decimal_number.quantize(quantize_exp, rounding=ROUND_HALF_UP)
# Return the rounded number as a float or as a Decimal depending on the context where it will be used.
return float(rounded_number) if isinstance(number, float) else rounded_number
# Example usage:
original_number = 3.14159
rounded_number = round_half_up(original_number, 2)
print("Original:", original_number)
print("Rounded:", rounded_number)
This function takes a floating point number and a precision value as arguments. It converts the number to a Decimal type, defines the precision for rounding, and then rounds the number according to the HALF_UP rule, which is the common method of rounding in many situations.
In the example usage, original_number is rounded to 2 decimal places, and the result is printed out. You can change the precision parameter to round to a different number of decimal places. The function returns the result as a float, but you can easily modify it to return a Decimal by removing the conversion to float in the return statement.