The FixedDecimal property of the Application object in Excel is a feature that allows for the automatic rounding of numbers entered into cells to a fixed number of decimal places. This is particularly useful in scenarios where consistent decimal precision is required across data entry, such as in financial or scientific applications, without manually formatting each cell. When enabled, any number typed into a worksheet will be rounded to the specified decimal places. For example, if FixedDecimal is set to True and FixedDecimalPlaces is set to 2, entering 123.456 will result in 123.46 being stored in the cell. It’s important to note that this property affects only data entry and not existing data or calculations, and it applies globally to the Excel application instance.
In xlwings, you can access this property through the app object, which represents the Excel application. The syntax for setting or getting the FixedDecimal property is straightforward, as it is a boolean property. Here’s the basic structure:
- Get the current value:
app.api.FixedDecimal - Set the value:
app.api.FixedDecimal = Trueorapp.api.FixedDecimal = False
To specify the number of decimal places, you use the FixedDecimalPlaces property in conjunction with FixedDecimal. The FixedDecimalPlaces property takes an integer value. For example, to set two decimal places: app.api.FixedDecimalPlaces = 2. It’s essential to set FixedDecimalPlaces before or after enabling FixedDecimal, depending on your needs. The typical workflow involves enabling the property, setting the decimal places, and then disabling it when done to avoid unintended rounding in other operations.
Below is a code example demonstrating the use of FixedDecimal with xlwings:
import xlwings as xw
# Connect to the active Excel application or start a new one
app = xw.apps.active
# Enable fixed decimal rounding
app.api.FixedDecimal = True
# Set the number of decimal places to 2
app.api.FixedDecimalPlaces = 2
# Now, any number entered in Excel will be rounded to 2 decimal places
# For instance, typing 45.678 in a cell will display as 45.68
# To demonstrate, add a value to a cell in a new workbook
wb = app.books.add()
ws = wb.sheets[0]
ws.range('A1').value = 45.678 # This will be rounded to 45.68 upon entry
print(f"Value in A1: {ws.range('A1').value}") # Output should be 45.68
# Disable fixed decimal rounding after use
app.api.FixedDecimal = False
# Optionally, reset FixedDecimalPlaces to 0 (default)
app.api.FixedDecimalPlaces = 0
# Close the workbook without saving
wb.close()
Leave a Reply