I have an Access database in which there is some data dumped into an Excel workbook via vba code. Some of the values have a lengthy decimal which I want to round to the nearest tenth. I don’t want the value rounded to the tenth if it is a whole number (i.e., I don’t want 45 rounded to 45.0), so I’m using the following code:
If Fix(rstTmpRegularAndOvertimeHours!regularhours) = rstTmpRegularAndOvertimeHours!regularhours Then objWS.cells(intRowCount, 6).Value = rstTmpRegularAndOvertimeHours!regularhours Else objWS.cells(intRowCount, 6).Value = Round(rstTmpRegularAndOvertimeHours!regularhours, 1) End If
The rounded value is displayed in the cell, however, the actual value entered is the unrounded value. For example, the value is 4.19999980926513, and when this code is run, the value 4.2 is displayed in the cell, but if you click on the cell you see that the actual value is still 4.19999980926513. And when the following line of code runs:
With objWS.PageSetup .Orientation = 2 .Zoom = False .FitToPagesWide = 1 .FitToPagesTall = 1 End With
The cell expands to show the whole value and shows 4.19999980926513 again. I am using similar code in other places and am getting the correct rounded value inserted into the spreadsheet. Any ideas?
Decimal fractions are challenging for binary systems.
Round() returns a double precision float. But 4.2 can not be stored exactly as a double. So instead the double value is an approximation of 4.2, and it’s the closest you can get with a double.
So what what you’re seeing in Excel is that actual double value. If you want to display it with a single decimal place — and then adjust the column width based on that — change the Excel column format to “Number” with 1 for the “decimal places” property.